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