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