Adding background style in the General status window settings.
[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 = nil;
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 = nil;
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 = nil;
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)showTestWindow
480 {
481     [self showCurrentTrackInfo];
482 }
483
484 - (void)quitMenuTunes
485 {
486     ITDebugLog(@"Quitting MenuTunes.");
487     [NSApp terminate:self];
488 }
489
490 //
491 //
492
493 - (void)closePreferences
494 {
495     ITDebugLog(@"Preferences closed.");
496     if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
497         [self setupHotKeys];
498     }
499 }
500
501 - (ITMTRemote *)currentRemote
502 {
503     return currentRemote;
504 }
505
506 //
507 //
508 // Hot key setup
509 //
510 //
511
512 - (void)clearHotKeys
513 {
514     NSEnumerator *hotKeyEnumerator = [[[ITHotKeyCenter sharedCenter] allHotKeys] objectEnumerator];
515     ITHotKey *nextHotKey;
516     ITDebugLog(@"Clearing hot keys.");
517     while ( (nextHotKey = [hotKeyEnumerator nextObject]) ) {
518         [[ITHotKeyCenter sharedCenter] unregisterHotKey:nextHotKey];
519     }
520     ITDebugLog(@"Done clearing hot keys.");
521 }
522
523 - (void)setupHotKeys
524 {
525     ITHotKey *hotKey;
526     ITDebugLog(@"Setting up hot keys.");
527     
528     if (playerRunningState == ITMTRemotePlayerNotRunning) {
529         return;
530     }
531     
532     if ([df objectForKey:@"PlayPause"] != nil) {
533         ITDebugLog(@"Setting up play pause hot key.");
534         hotKey = [[ITHotKey alloc] init];
535         [hotKey setName:@"PlayPause"];
536         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PlayPause"]]];
537         [hotKey setTarget:self];
538         [hotKey setAction:@selector(playPause)];
539         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
540     }
541     
542     if ([df objectForKey:@"NextTrack"] != nil) {
543         ITDebugLog(@"Setting up next track hot key.");
544         hotKey = [[ITHotKey alloc] init];
545         [hotKey setName:@"NextTrack"];
546         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"NextTrack"]]];
547         [hotKey setTarget:self];
548         [hotKey setAction:@selector(nextSong)];
549         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
550     }
551     
552     if ([df objectForKey:@"PrevTrack"] != nil) {
553         ITDebugLog(@"Setting up previous track hot key.");
554         hotKey = [[ITHotKey alloc] init];
555         [hotKey setName:@"PrevTrack"];
556         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PrevTrack"]]];
557         [hotKey setTarget:self];
558         [hotKey setAction:@selector(prevSong)];
559         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
560     }
561     
562     if ([df objectForKey:@"ShowPlayer"] != nil) {
563         ITDebugLog(@"Setting up show player hot key.");
564         hotKey = [[ITHotKey alloc] init];
565         [hotKey setName:@"ShowPlayer"];
566         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
567         [hotKey setTarget:self];
568         [hotKey setAction:@selector(showPlayer)];
569         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
570     }
571     
572     if ([df objectForKey:@"TrackInfo"] != nil) {
573         ITDebugLog(@"Setting up track info hot key.");
574         hotKey = [[ITHotKey alloc] init];
575         [hotKey setName:@"TrackInfo"];
576         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"TrackInfo"]]];
577         [hotKey setTarget:self];
578         [hotKey setAction:@selector(showCurrentTrackInfo)];
579         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
580     }
581     
582     if ([df objectForKey:@"UpcomingSongs"] != nil) {
583         ITDebugLog(@"Setting up upcoming songs hot key.");
584         hotKey = [[ITHotKey alloc] init];
585         [hotKey setName:@"UpcomingSongs"];
586         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"UpcomingSongs"]]];
587         [hotKey setTarget:self];
588         [hotKey setAction:@selector(showUpcomingSongs)];
589         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
590     }
591     
592     if ([df objectForKey:@"ToggleLoop"] != nil) {
593         ITDebugLog(@"Setting up toggle loop hot key.");
594         hotKey = [[ITHotKey alloc] init];
595         [hotKey setName:@"ToggleLoop"];
596         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleLoop"]]];
597         [hotKey setTarget:self];
598         [hotKey setAction:@selector(toggleLoop)];
599         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
600     }
601     
602     if ([df objectForKey:@"ToggleShuffle"] != nil) {
603         ITDebugLog(@"Setting up toggle shuffle hot key.");
604         hotKey = [[ITHotKey alloc] init];
605         [hotKey setName:@"ToggleShuffle"];
606         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShuffle"]]];
607         [hotKey setTarget:self];
608         [hotKey setAction:@selector(toggleShuffle)];
609         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
610     }
611     
612     if ([df objectForKey:@"IncrementVolume"] != nil) {
613         ITDebugLog(@"Setting up increment volume hot key.");
614         hotKey = [[ITHotKey alloc] init];
615         [hotKey setName:@"IncrementVolume"];
616         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementVolume"]]];
617         [hotKey setTarget:self];
618         [hotKey setAction:@selector(incrementVolume)];
619         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
620     }
621     
622     if ([df objectForKey:@"DecrementVolume"] != nil) {
623         ITDebugLog(@"Setting up decrement volume hot key.");
624         hotKey = [[ITHotKey alloc] init];
625         [hotKey setName:@"DecrementVolume"];
626         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementVolume"]]];
627         [hotKey setTarget:self];
628         [hotKey setAction:@selector(decrementVolume)];
629         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
630     }
631     
632     if ([df objectForKey:@"IncrementRating"] != nil) {
633         ITDebugLog(@"Setting up increment rating hot key.");
634         hotKey = [[ITHotKey alloc] init];
635         [hotKey setName:@"IncrementRating"];
636         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementRating"]]];
637         [hotKey setTarget:self];
638         [hotKey setAction:@selector(incrementRating)];
639         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
640     }
641     
642     if ([df objectForKey:@"DecrementRating"] != nil) {
643         ITDebugLog(@"Setting up decrement rating hot key.");
644         hotKey = [[ITHotKey alloc] init];
645         [hotKey setName:@"DecrementRating"];
646         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementRating"]]];
647         [hotKey setTarget:self];
648         [hotKey setAction:@selector(decrementRating)];
649         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
650     }
651     ITDebugLog(@"Finished setting up hot keys.");
652 }
653
654 - (void)showCurrentTrackInfo
655 {
656     ITMTRemotePlayerSource  source      = 0;
657     NSString               *title       = nil;
658     NSString               *album       = nil;
659     NSString               *artist      = nil;
660     NSString               *time        = nil;
661     NSString               *track       = nil;
662     int                     rating      = -1;
663     
664     NS_DURING
665         source      = [[self currentRemote] currentSource];
666         title       = [[self currentRemote] currentSongTitle];
667     NS_HANDLER
668         [self networkError:localException];
669     NS_ENDHANDLER
670     
671     ITDebugLog(@"Showing track info status window.");
672     
673     if ( title ) {
674
675         if ( [df boolForKey:@"showAlbum"] ) {
676             NS_DURING
677                 album = [[self currentRemote] currentSongAlbum];
678             NS_HANDLER
679                 [self networkError:localException];
680             NS_ENDHANDLER
681         }
682
683         if ( [df boolForKey:@"showArtist"] ) {
684             NS_DURING
685                 artist = [[self currentRemote] currentSongArtist];
686             NS_HANDLER
687                 [self networkError:localException];
688             NS_ENDHANDLER
689         }
690
691         if ( [df boolForKey:@"showTime"] ) {
692             NS_DURING
693                 time = [NSString stringWithFormat:@"%@: %@ / %@",
694                 @"Time",
695                 [[self currentRemote] currentSongElapsed],
696                 [[self currentRemote] currentSongLength]];
697             NS_HANDLER
698                 [self networkError:localException];
699             NS_ENDHANDLER
700         }
701
702         if ( [df boolForKey:@"showTrackNumber"] ) {
703             int trackNo    = 0;
704             int trackCount = 0;
705             
706             NS_DURING
707                 trackNo    = [[self currentRemote] currentSongTrack];
708                 trackCount = [[self currentRemote] currentAlbumTrackCount];
709             NS_HANDLER
710                 [self networkError:localException];
711             NS_ENDHANDLER
712             
713             if ( (trackNo > 0) || (trackCount > 0) ) {
714                 track = [NSString stringWithFormat:@"%@: %i %@ %i",
715                     @"Track", trackNo, @"of", trackCount];
716             }
717         }
718
719         if ( [df boolForKey:@"showTrackRating"] ) {
720             float currentRating = 0;
721             
722             NS_DURING
723                 currentRating = [[self currentRemote] currentSongRating];
724             NS_HANDLER
725                 [self networkError:localException];
726             NS_ENDHANDLER
727             
728             if (currentRating >= 0.0) {
729                 rating = ( currentRating * 5 );
730             }
731         }
732         
733     } else {
734         title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
735     }
736
737     [statusWindowController showSongInfoWindowWithSource:source
738                                                    title:title
739                                                    album:album
740                                                   artist:artist
741                                                     time:time
742                                                    track:track
743                                                   rating:rating];
744 }
745
746 - (void)showUpcomingSongs
747 {
748     int numSongs = 0;
749     NS_DURING
750         numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
751     NS_HANDLER
752         [self networkError:localException];
753     NS_ENDHANDLER
754     
755     ITDebugLog(@"Showing upcoming songs status window.");
756     NS_DURING
757         if (numSongs > 0) {
758             int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
759             NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
760             int curTrack = [[self currentRemote] currentSongIndex];
761             int i;
762     
763             for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
764                 if (i <= numSongs) {
765                     [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
766                 }
767             }
768             
769             if ([songList count] == 0) {
770                 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
771             }
772             
773             [statusWindowController showUpcomingSongsWindowWithTitles:songList];
774         } else {
775             [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
776         }
777     NS_HANDLER
778         [self networkError:localException];
779     NS_ENDHANDLER
780 }
781
782 - (void)incrementVolume
783 {
784     NS_DURING
785         float volume  = [[self currentRemote] volume];
786         float dispVol = volume;
787         ITDebugLog(@"Incrementing volume.");
788         volume  += 0.110;
789         dispVol += 0.100;
790         
791         if (volume > 1.0) {
792             volume  = 1.0;
793             dispVol = 1.0;
794         }
795     
796         ITDebugLog(@"Setting volume to %f", volume);
797         [[self currentRemote] setVolume:volume];
798     
799         // Show volume status window
800         [statusWindowController showVolumeWindowWithLevel:dispVol];
801     NS_HANDLER
802         [self networkError:localException];
803     NS_ENDHANDLER
804 }
805
806 - (void)decrementVolume
807 {
808     NS_DURING
809         float volume  = [[self currentRemote] volume];
810         float dispVol = volume;
811         ITDebugLog(@"Decrementing volume.");
812         volume  -= 0.090;
813         dispVol -= 0.100;
814     
815         if (volume < 0.0) {
816             volume  = 0.0;
817             dispVol = 0.0;
818         }
819         
820         ITDebugLog(@"Setting volume to %f", volume);
821         [[self currentRemote] setVolume:volume];
822         
823         //Show volume status window
824         [statusWindowController showVolumeWindowWithLevel:dispVol];
825     NS_HANDLER
826         [self networkError:localException];
827     NS_ENDHANDLER
828 }
829
830 - (void)incrementRating
831 {
832     NS_DURING
833         float rating = [[self currentRemote] currentSongRating];
834         ITDebugLog(@"Incrementing rating.");
835         
836         if ([[self currentRemote] currentPlaylistIndex] == 0) {
837             ITDebugLog(@"No song playing, rating change aborted.");
838             return;
839         }
840         
841         rating += 0.2;
842         if (rating > 1.0) {
843             rating = 1.0;
844         }
845         ITDebugLog(@"Setting rating to %f", rating);
846         [[self currentRemote] setCurrentSongRating:rating];
847         
848         //Show rating status window
849         [statusWindowController showRatingWindowWithRating:rating];
850     NS_HANDLER
851         [self networkError:localException];
852     NS_ENDHANDLER
853 }
854
855 - (void)decrementRating
856 {
857     NS_DURING
858         float rating = [[self currentRemote] currentSongRating];
859         ITDebugLog(@"Decrementing rating.");
860         
861         if ([[self currentRemote] currentPlaylistIndex] == 0) {
862             ITDebugLog(@"No song playing, rating change aborted.");
863             return;
864         }
865         
866         rating -= 0.2;
867         if (rating < 0.0) {
868             rating = 0.0;
869         }
870         ITDebugLog(@"Setting rating to %f", rating);
871         [[self currentRemote] setCurrentSongRating:rating];
872         
873         //Show rating status window
874         [statusWindowController showRatingWindowWithRating:rating];
875     NS_HANDLER
876         [self networkError:localException];
877     NS_ENDHANDLER
878 }
879
880 - (void)toggleLoop
881 {
882     NS_DURING
883         ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
884         ITDebugLog(@"Toggling repeat mode.");
885         switch (repeatMode) {
886             case ITMTRemotePlayerRepeatOff:
887                 repeatMode = ITMTRemotePlayerRepeatAll;
888             break;
889             case ITMTRemotePlayerRepeatAll:
890                 repeatMode = ITMTRemotePlayerRepeatOne;
891             break;
892             case ITMTRemotePlayerRepeatOne:
893                 repeatMode = ITMTRemotePlayerRepeatOff;
894             break;
895         }
896         ITDebugLog(@"Setting repeat mode to %i", repeatMode);
897         [[self currentRemote] setRepeatMode:repeatMode];
898         
899         //Show loop status window
900         [statusWindowController showRepeatWindowWithMode:repeatMode];
901     NS_HANDLER
902         [self networkError:localException];
903     NS_ENDHANDLER
904 }
905
906 - (void)toggleShuffle
907 {
908     NS_DURING
909         BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
910         ITDebugLog(@"Toggling shuffle mode.");
911         [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
912         //Show shuffle status window
913         ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
914         [statusWindowController showShuffleWindow:newShuffleEnabled];
915     NS_HANDLER
916         [self networkError:localException];
917     NS_ENDHANDLER
918 }
919
920 - (void)registerNowOK
921 {
922     [[StatusWindow sharedWindow] setLocked:NO];
923     [[StatusWindow sharedWindow] vanish:self];
924     [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
925
926     [self blingNow];
927 }
928
929 - (void)registerNowCancel
930 {
931     [[StatusWindow sharedWindow] setLocked:NO];
932     [[StatusWindow sharedWindow] vanish:self];
933     [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
934
935     [NSApp terminate:self];
936 }
937
938 /*************************************************************************/
939 #pragma mark -
940 #pragma mark NETWORK HANDLERS
941 /*************************************************************************/
942
943 - (void)setServerStatus:(BOOL)newStatus
944 {
945     if (newStatus) {
946         //Turn on
947         [networkController setServerStatus:YES];
948     } else {
949         //Tear down
950         [networkController setServerStatus:NO];
951     }
952 }
953
954 - (int)connectToServer
955 {
956     int result;
957     ITDebugLog(@"Attempting to connect to shared remote.");
958     result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
959     //Connect
960     if (result == 1) {
961         [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
962         currentRemote = [[[networkController networkObject] remote] retain];
963         [self timerUpdate];
964         ITDebugLog(@"Connection successful.");
965         return 1;
966     } else if (result == 0) {
967         ITDebugLog(@"Connection failed.");
968         currentRemote = [remoteArray objectAtIndex:0];
969         return 0;
970     } else {
971         //Do something about the password being invalid
972         ITDebugLog(@"Connection failed.");
973         currentRemote = [remoteArray objectAtIndex:0];
974         return -1;
975     }
976 }
977
978 - (BOOL)disconnectFromServer
979 {
980     ITDebugLog(@"Disconnecting from shared remote.");
981     //Disconnect
982     [currentRemote release];
983     currentRemote = [remoteArray objectAtIndex:0];
984     [networkController disconnect];
985     [self timerUpdate];
986     return YES;
987 }
988
989 - (void)checkForRemoteServer:(NSTimer *)timer
990 {
991     ITDebugLog(@"Checking for remote server.");
992     if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
993         ITDebugLog(@"Remote server found.");
994         [timer invalidate];
995         if (![networkController isConnectedToServer]) {
996             [[StatusWindowController sharedController] showReconnectQueryWindow];
997         }
998     } else {
999         ITDebugLog(@"Remote server not found.");
1000     }
1001 }
1002
1003 - (void)networkError:(NSException *)exception
1004 {
1005     ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1006     NSLog(@"%@", [exception reason]);
1007     if ([[exception name] isEqualToString:NSPortTimeoutException] && [networkController isConnectedToServer]) {
1008         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);
1009         if ([self disconnectFromServer]) {
1010             [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1011             [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
1012         } else {
1013             ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1014         }
1015     }
1016 }
1017
1018 - (void)reconnect
1019 {
1020     if ([self connectToServer] == 0) {
1021         [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
1022     }
1023     [[StatusWindow sharedWindow] setLocked:NO];
1024     [[StatusWindow sharedWindow] vanish:self];
1025     [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1026 }
1027
1028 - (void)cancelReconnect
1029 {
1030     [[StatusWindow sharedWindow] setLocked:NO];
1031     [[StatusWindow sharedWindow] vanish:self];
1032     [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1033 }
1034
1035 /*************************************************************************/
1036 #pragma mark -
1037 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1038 /*************************************************************************/
1039
1040 - (void)applicationLaunched:(NSNotification *)note
1041 {
1042     NS_DURING
1043         if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]]) {
1044             ITDebugLog(@"Remote application launched.");
1045             playerRunningState = ITMTRemotePlayerRunning;
1046             [[self currentRemote] begin];
1047             [self setLatestSongIdentifier:@""];
1048             [self timerUpdate];
1049             refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1050                                 target:self
1051                                 selector:@selector(timerUpdate)
1052                                 userInfo:nil
1053                                 repeats:YES] retain];
1054             //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1055             [self setupHotKeys];
1056         }
1057     NS_HANDLER
1058         [self networkError:localException];
1059     NS_ENDHANDLER
1060 }
1061
1062  - (void)applicationTerminated:(NSNotification *)note
1063  {
1064     NS_DURING
1065         if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]]) {
1066             ITDebugLog(@"Remote application terminated.");
1067             [[self currentRemote] halt];
1068             [refreshTimer invalidate];
1069             [refreshTimer release];
1070             refreshTimer = nil;
1071             [self clearHotKeys];
1072             playerRunningState = ITMTRemotePlayerNotRunning;
1073         }
1074     NS_HANDLER
1075         [self networkError:localException];
1076     NS_ENDHANDLER
1077  }
1078
1079
1080 /*************************************************************************/
1081 #pragma mark -
1082 #pragma mark NSApplication DELEGATE METHODS
1083 /*************************************************************************/
1084
1085 - (void)applicationWillTerminate:(NSNotification *)note
1086 {
1087     [networkController stopRemoteServerSearch];
1088     [self clearHotKeys];
1089     [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1090 }
1091
1092
1093 /*************************************************************************/
1094 #pragma mark -
1095 #pragma mark DEALLOCATION METHOD
1096 /*************************************************************************/
1097
1098 - (void)dealloc
1099 {
1100     [self applicationTerminated:nil];
1101     [bling release];
1102     [statusItem release];
1103     [statusWindowController release];
1104     [menuController release];
1105     [networkController release];
1106     [super dealloc];
1107 }
1108
1109 @end