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