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