Fixed a crash when unchecking share this player. Also trying to make the
[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         if ([[networkController networkObject] remote] == nil) {
294             [self networkError:nil];
295         }
296     }
297     
298     if ( [self songChanged] && (timerUpdating != YES) ) {
299         ITDebugLog(@"The song changed.");
300         timerUpdating = YES;
301         
302         NS_DURING
303             latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
304             [menuController rebuildSubmenus];
305     
306             if ( [df boolForKey:@"showSongInfoOnChange"] ) {
307                 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
308             }
309             
310             [self setLatestSongIdentifier:[[self currentRemote] playerStateUniqueIdentifier]];
311         NS_HANDLER
312             [self networkError:localException];
313         NS_ENDHANDLER
314         
315         timerUpdating = NO;
316     }
317 }
318
319 - (void)menuClicked
320 {
321     ITDebugLog(@"Menu clicked.");
322     if ([networkController isConnectedToServer]) {
323         //Used the cached version
324         return;
325     }
326     
327     NS_DURING
328         if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
329             [statusItem setMenu:[menuController menu]];
330         } else {
331             [statusItem setMenu:[menuController menuForNoPlayer]];
332         }
333     NS_HANDLER
334         [self networkError:localException];
335     NS_ENDHANDLER
336 }
337
338 //
339 //
340 // Menu Selectors
341 //
342 //
343
344 - (void)playPause
345 {
346     NS_DURING
347         ITMTRemotePlayerPlayingState state = [[self currentRemote] playerPlayingState];
348         ITDebugLog(@"Play/Pause toggled");
349         if (state == ITMTRemotePlayerPlaying) {
350             [[self currentRemote] pause];
351         } else if ((state == ITMTRemotePlayerForwarding) || (state == ITMTRemotePlayerRewinding)) {
352             [[self currentRemote] pause];
353             [[self currentRemote] play];
354         } else {
355             [[self currentRemote] play];
356         }
357     NS_HANDLER
358         [self networkError:localException];
359     NS_ENDHANDLER
360     
361     [self timerUpdate];
362 }
363
364 - (void)nextSong
365 {
366     ITDebugLog(@"Going to next song.");
367     NS_DURING
368         [[self currentRemote] goToNextSong];
369     NS_HANDLER
370         [self networkError:localException];
371     NS_ENDHANDLER
372     [self timerUpdate];
373 }
374
375 - (void)prevSong
376 {
377     ITDebugLog(@"Going to previous song.");
378     NS_DURING
379         [[self currentRemote] goToPreviousSong];
380     NS_HANDLER
381         [self networkError:localException];
382     NS_ENDHANDLER
383     [self timerUpdate];
384 }
385
386 - (void)fastForward
387 {
388     ITDebugLog(@"Fast forwarding.");
389     NS_DURING
390         [[self currentRemote] forward];
391     NS_HANDLER
392         [self networkError:localException];
393     NS_ENDHANDLER
394     [self timerUpdate];
395 }
396
397 - (void)rewind
398 {
399     ITDebugLog(@"Rewinding.");
400     NS_DURING
401         [[self currentRemote] rewind];
402     NS_HANDLER
403         [self networkError:localException];
404     NS_ENDHANDLER
405     [self timerUpdate];
406 }
407
408 - (void)selectPlaylistAtIndex:(int)index
409 {
410     ITDebugLog(@"Selecting playlist %i", index);
411     NS_DURING
412         [[self currentRemote] switchToPlaylistAtIndex:index];
413     NS_HANDLER
414         [self networkError:localException];
415     NS_ENDHANDLER
416     [self timerUpdate];
417 }
418
419 - (void)selectSongAtIndex:(int)index
420 {
421     ITDebugLog(@"Selecting song %i", index);
422     NS_DURING
423         [[self currentRemote] switchToSongAtIndex:index];
424     NS_HANDLER
425         [self networkError:localException];
426     NS_ENDHANDLER
427     [self timerUpdate];
428 }
429
430 - (void)selectSongRating:(int)rating
431 {
432     ITDebugLog(@"Selecting song rating %i", rating);
433     NS_DURING
434         [[self currentRemote] setCurrentSongRating:(float)rating / 100.0];
435     NS_HANDLER
436         [self networkError:localException];
437     NS_ENDHANDLER
438     [self timerUpdate];
439 }
440
441 - (void)selectEQPresetAtIndex:(int)index
442 {
443     ITDebugLog(@"Selecting EQ preset %i", index);
444     NS_DURING
445         [[self currentRemote] switchToEQAtIndex:index];
446     NS_HANDLER
447         [self networkError:localException];
448     NS_ENDHANDLER
449     [self timerUpdate];
450 }
451
452 - (void)showPlayer
453 {
454     ITDebugLog(@"Beginning show player.");
455     if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
456         ITDebugLog(@"Showing player interface.");
457         NS_DURING
458             [[self currentRemote] showPrimaryInterface];
459         NS_HANDLER
460             [self networkError:localException];
461         NS_ENDHANDLER
462     } else {
463         ITDebugLog(@"Launching player.");
464         NS_DURING
465             if (![[NSWorkspace sharedWorkspace] launchApplication:[[self currentRemote] playerFullName]]) {
466                 ITDebugLog(@"Error Launching Player");
467             }
468         NS_HANDLER
469             [self networkError:localException];
470         NS_ENDHANDLER
471     }
472     ITDebugLog(@"Finished show player.");
473 }
474
475 - (void)showPreferences
476 {
477     ITDebugLog(@"Show preferences.");
478     [[PreferencesController sharedPrefs] showPrefsWindow:self];
479 }
480
481 - (void)showTestWindow
482 {
483     [self showCurrentTrackInfo];
484 }
485
486 - (void)quitMenuTunes
487 {
488     ITDebugLog(@"Quitting MenuTunes.");
489     [NSApp terminate:self];
490 }
491
492 //
493 //
494
495 - (void)closePreferences
496 {
497     ITDebugLog(@"Preferences closed.");
498     if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
499         [self setupHotKeys];
500     }
501 }
502
503 - (ITMTRemote *)currentRemote
504 {
505     return currentRemote;
506 }
507
508 //
509 //
510 // Hot key setup
511 //
512 //
513
514 - (void)clearHotKeys
515 {
516     NSEnumerator *hotKeyEnumerator = [[[ITHotKeyCenter sharedCenter] allHotKeys] objectEnumerator];
517     ITHotKey *nextHotKey;
518     ITDebugLog(@"Clearing hot keys.");
519     while ( (nextHotKey = [hotKeyEnumerator nextObject]) ) {
520         [[ITHotKeyCenter sharedCenter] unregisterHotKey:nextHotKey];
521     }
522     ITDebugLog(@"Done clearing hot keys.");
523 }
524
525 - (void)setupHotKeys
526 {
527     ITHotKey *hotKey;
528     ITDebugLog(@"Setting up hot keys.");
529     
530     if (playerRunningState == ITMTRemotePlayerNotRunning) {
531         return;
532     }
533     
534     if ([df objectForKey:@"PlayPause"] != nil) {
535         ITDebugLog(@"Setting up play pause hot key.");
536         hotKey = [[ITHotKey alloc] init];
537         [hotKey setName:@"PlayPause"];
538         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PlayPause"]]];
539         [hotKey setTarget:self];
540         [hotKey setAction:@selector(playPause)];
541         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
542     }
543     
544     if ([df objectForKey:@"NextTrack"] != nil) {
545         ITDebugLog(@"Setting up next track hot key.");
546         hotKey = [[ITHotKey alloc] init];
547         [hotKey setName:@"NextTrack"];
548         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"NextTrack"]]];
549         [hotKey setTarget:self];
550         [hotKey setAction:@selector(nextSong)];
551         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
552     }
553     
554     if ([df objectForKey:@"PrevTrack"] != nil) {
555         ITDebugLog(@"Setting up previous track hot key.");
556         hotKey = [[ITHotKey alloc] init];
557         [hotKey setName:@"PrevTrack"];
558         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PrevTrack"]]];
559         [hotKey setTarget:self];
560         [hotKey setAction:@selector(prevSong)];
561         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
562     }
563     
564     if ([df objectForKey:@"ShowPlayer"] != nil) {
565         ITDebugLog(@"Setting up show player hot key.");
566         hotKey = [[ITHotKey alloc] init];
567         [hotKey setName:@"ShowPlayer"];
568         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
569         [hotKey setTarget:self];
570         [hotKey setAction:@selector(showPlayer)];
571         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
572     }
573     
574     if ([df objectForKey:@"TrackInfo"] != nil) {
575         ITDebugLog(@"Setting up track info hot key.");
576         hotKey = [[ITHotKey alloc] init];
577         [hotKey setName:@"TrackInfo"];
578         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"TrackInfo"]]];
579         [hotKey setTarget:self];
580         [hotKey setAction:@selector(showCurrentTrackInfo)];
581         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
582     }
583     
584     if ([df objectForKey:@"UpcomingSongs"] != nil) {
585         ITDebugLog(@"Setting up upcoming songs hot key.");
586         hotKey = [[ITHotKey alloc] init];
587         [hotKey setName:@"UpcomingSongs"];
588         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"UpcomingSongs"]]];
589         [hotKey setTarget:self];
590         [hotKey setAction:@selector(showUpcomingSongs)];
591         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
592     }
593     
594     if ([df objectForKey:@"ToggleLoop"] != nil) {
595         ITDebugLog(@"Setting up toggle loop hot key.");
596         hotKey = [[ITHotKey alloc] init];
597         [hotKey setName:@"ToggleLoop"];
598         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleLoop"]]];
599         [hotKey setTarget:self];
600         [hotKey setAction:@selector(toggleLoop)];
601         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
602     }
603     
604     if ([df objectForKey:@"ToggleShuffle"] != nil) {
605         ITDebugLog(@"Setting up toggle shuffle hot key.");
606         hotKey = [[ITHotKey alloc] init];
607         [hotKey setName:@"ToggleShuffle"];
608         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShuffle"]]];
609         [hotKey setTarget:self];
610         [hotKey setAction:@selector(toggleShuffle)];
611         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
612     }
613     
614     if ([df objectForKey:@"IncrementVolume"] != nil) {
615         ITDebugLog(@"Setting up increment volume hot key.");
616         hotKey = [[ITHotKey alloc] init];
617         [hotKey setName:@"IncrementVolume"];
618         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementVolume"]]];
619         [hotKey setTarget:self];
620         [hotKey setAction:@selector(incrementVolume)];
621         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
622     }
623     
624     if ([df objectForKey:@"DecrementVolume"] != nil) {
625         ITDebugLog(@"Setting up decrement volume hot key.");
626         hotKey = [[ITHotKey alloc] init];
627         [hotKey setName:@"DecrementVolume"];
628         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementVolume"]]];
629         [hotKey setTarget:self];
630         [hotKey setAction:@selector(decrementVolume)];
631         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
632     }
633     
634     if ([df objectForKey:@"IncrementRating"] != nil) {
635         ITDebugLog(@"Setting up increment rating hot key.");
636         hotKey = [[ITHotKey alloc] init];
637         [hotKey setName:@"IncrementRating"];
638         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementRating"]]];
639         [hotKey setTarget:self];
640         [hotKey setAction:@selector(incrementRating)];
641         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
642     }
643     
644     if ([df objectForKey:@"DecrementRating"] != nil) {
645         ITDebugLog(@"Setting up decrement rating hot key.");
646         hotKey = [[ITHotKey alloc] init];
647         [hotKey setName:@"DecrementRating"];
648         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementRating"]]];
649         [hotKey setTarget:self];
650         [hotKey setAction:@selector(decrementRating)];
651         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
652     }
653     ITDebugLog(@"Finished setting up hot keys.");
654 }
655
656 - (void)showCurrentTrackInfo
657 {
658     ITMTRemotePlayerSource  source      = 0;
659     NSString               *title       = nil;
660     NSString               *album       = nil;
661     NSString               *artist      = nil;
662     NSString               *time        = nil;
663     NSString               *track       = nil;
664     int                     rating      = -1;
665     
666     NS_DURING
667         source      = [[self currentRemote] currentSource];
668         title       = [[self currentRemote] currentSongTitle];
669     NS_HANDLER
670         [self networkError:localException];
671     NS_ENDHANDLER
672     
673     ITDebugLog(@"Showing track info status window.");
674     
675     if ( title ) {
676
677         if ( [df boolForKey:@"showAlbum"] ) {
678             NS_DURING
679                 album = [[self currentRemote] currentSongAlbum];
680             NS_HANDLER
681                 [self networkError:localException];
682             NS_ENDHANDLER
683         }
684
685         if ( [df boolForKey:@"showArtist"] ) {
686             NS_DURING
687                 artist = [[self currentRemote] currentSongArtist];
688             NS_HANDLER
689                 [self networkError:localException];
690             NS_ENDHANDLER
691         }
692
693         if ( [df boolForKey:@"showTime"] ) {
694             NS_DURING
695                 time = [NSString stringWithFormat:@"%@: %@ / %@",
696                 @"Time",
697                 [[self currentRemote] currentSongElapsed],
698                 [[self currentRemote] currentSongLength]];
699             NS_HANDLER
700                 [self networkError:localException];
701             NS_ENDHANDLER
702         }
703
704         if ( [df boolForKey:@"showTrackNumber"] ) {
705             int trackNo    = 0;
706             int trackCount = 0;
707             
708             NS_DURING
709                 trackNo    = [[self currentRemote] currentSongTrack];
710                 trackCount = [[self currentRemote] currentAlbumTrackCount];
711             NS_HANDLER
712                 [self networkError:localException];
713             NS_ENDHANDLER
714             
715             if ( (trackNo > 0) || (trackCount > 0) ) {
716                 track = [NSString stringWithFormat:@"%@: %i %@ %i",
717                     @"Track", trackNo, @"of", trackCount];
718             }
719         }
720
721         if ( [df boolForKey:@"showTrackRating"] ) {
722             float currentRating = 0;
723             
724             NS_DURING
725                 currentRating = [[self currentRemote] currentSongRating];
726             NS_HANDLER
727                 [self networkError:localException];
728             NS_ENDHANDLER
729             
730             if (currentRating >= 0.0) {
731                 rating = ( currentRating * 5 );
732             }
733         }
734         
735     } else {
736         title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
737     }
738
739     [statusWindowController showSongInfoWindowWithSource:source
740                                                    title:title
741                                                    album:album
742                                                   artist:artist
743                                                     time:time
744                                                    track:track
745                                                   rating:rating];
746 }
747
748 - (void)showUpcomingSongs
749 {
750     int numSongs = 0;
751     NS_DURING
752         numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
753     NS_HANDLER
754         [self networkError:localException];
755     NS_ENDHANDLER
756     
757     ITDebugLog(@"Showing upcoming songs status window.");
758     NS_DURING
759         if (numSongs > 0) {
760             int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
761             NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
762             int curTrack = [[self currentRemote] currentSongIndex];
763             int i;
764     
765             for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
766                 if (i <= numSongs) {
767                     [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
768                 }
769             }
770             
771             if ([songList count] == 0) {
772                 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
773             }
774             
775             [statusWindowController showUpcomingSongsWindowWithTitles:songList];
776         } else {
777             [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
778         }
779     NS_HANDLER
780         [self networkError:localException];
781     NS_ENDHANDLER
782 }
783
784 - (void)incrementVolume
785 {
786     NS_DURING
787         float volume  = [[self currentRemote] volume];
788         float dispVol = volume;
789         ITDebugLog(@"Incrementing volume.");
790         volume  += 0.110;
791         dispVol += 0.100;
792         
793         if (volume > 1.0) {
794             volume  = 1.0;
795             dispVol = 1.0;
796         }
797     
798         ITDebugLog(@"Setting volume to %f", volume);
799         [[self currentRemote] setVolume:volume];
800     
801         // Show volume status window
802         [statusWindowController showVolumeWindowWithLevel:dispVol];
803     NS_HANDLER
804         [self networkError:localException];
805     NS_ENDHANDLER
806 }
807
808 - (void)decrementVolume
809 {
810     NS_DURING
811         float volume  = [[self currentRemote] volume];
812         float dispVol = volume;
813         ITDebugLog(@"Decrementing volume.");
814         volume  -= 0.090;
815         dispVol -= 0.100;
816     
817         if (volume < 0.0) {
818             volume  = 0.0;
819             dispVol = 0.0;
820         }
821         
822         ITDebugLog(@"Setting volume to %f", volume);
823         [[self currentRemote] setVolume:volume];
824         
825         //Show volume status window
826         [statusWindowController showVolumeWindowWithLevel:dispVol];
827     NS_HANDLER
828         [self networkError:localException];
829     NS_ENDHANDLER
830 }
831
832 - (void)incrementRating
833 {
834     NS_DURING
835         float rating = [[self currentRemote] currentSongRating];
836         ITDebugLog(@"Incrementing rating.");
837         
838         if ([[self currentRemote] currentPlaylistIndex] == 0) {
839             ITDebugLog(@"No song playing, rating change aborted.");
840             return;
841         }
842         
843         rating += 0.2;
844         if (rating > 1.0) {
845             rating = 1.0;
846         }
847         ITDebugLog(@"Setting rating to %f", rating);
848         [[self currentRemote] setCurrentSongRating:rating];
849         
850         //Show rating status window
851         [statusWindowController showRatingWindowWithRating:rating];
852     NS_HANDLER
853         [self networkError:localException];
854     NS_ENDHANDLER
855 }
856
857 - (void)decrementRating
858 {
859     NS_DURING
860         float rating = [[self currentRemote] currentSongRating];
861         ITDebugLog(@"Decrementing rating.");
862         
863         if ([[self currentRemote] currentPlaylistIndex] == 0) {
864             ITDebugLog(@"No song playing, rating change aborted.");
865             return;
866         }
867         
868         rating -= 0.2;
869         if (rating < 0.0) {
870             rating = 0.0;
871         }
872         ITDebugLog(@"Setting rating to %f", rating);
873         [[self currentRemote] setCurrentSongRating:rating];
874         
875         //Show rating status window
876         [statusWindowController showRatingWindowWithRating:rating];
877     NS_HANDLER
878         [self networkError:localException];
879     NS_ENDHANDLER
880 }
881
882 - (void)toggleLoop
883 {
884     NS_DURING
885         ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
886         ITDebugLog(@"Toggling repeat mode.");
887         switch (repeatMode) {
888             case ITMTRemotePlayerRepeatOff:
889                 repeatMode = ITMTRemotePlayerRepeatAll;
890             break;
891             case ITMTRemotePlayerRepeatAll:
892                 repeatMode = ITMTRemotePlayerRepeatOne;
893             break;
894             case ITMTRemotePlayerRepeatOne:
895                 repeatMode = ITMTRemotePlayerRepeatOff;
896             break;
897         }
898         ITDebugLog(@"Setting repeat mode to %i", repeatMode);
899         [[self currentRemote] setRepeatMode:repeatMode];
900         
901         //Show loop status window
902         [statusWindowController showRepeatWindowWithMode:repeatMode];
903     NS_HANDLER
904         [self networkError:localException];
905     NS_ENDHANDLER
906 }
907
908 - (void)toggleShuffle
909 {
910     NS_DURING
911         BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
912         ITDebugLog(@"Toggling shuffle mode.");
913         [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
914         //Show shuffle status window
915         ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
916         [statusWindowController showShuffleWindow:newShuffleEnabled];
917     NS_HANDLER
918         [self networkError:localException];
919     NS_ENDHANDLER
920 }
921
922 - (void)registerNowOK
923 {
924     [[StatusWindow sharedWindow] setLocked:NO];
925     [[StatusWindow sharedWindow] vanish:self];
926     [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
927
928     [self blingNow];
929 }
930
931 - (void)registerNowCancel
932 {
933     [[StatusWindow sharedWindow] setLocked:NO];
934     [[StatusWindow sharedWindow] vanish:self];
935     [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
936
937     [NSApp terminate:self];
938 }
939
940 /*************************************************************************/
941 #pragma mark -
942 #pragma mark NETWORK HANDLERS
943 /*************************************************************************/
944
945 - (void)setServerStatus:(BOOL)newStatus
946 {
947     if (newStatus) {
948         //Turn on
949         [networkController setServerStatus:YES];
950     } else {
951         //Tear down
952         [networkController setServerStatus:NO];
953     }
954 }
955
956 - (int)connectToServer
957 {
958     int result;
959     ITDebugLog(@"Attempting to connect to shared remote.");
960     result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
961     //Connect
962     if (result == 1) {
963         [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
964         currentRemote = [[[networkController networkObject] remote] retain];
965         [refreshTimer invalidate];
966         refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
967                                 target:self
968                                 selector:@selector(timerUpdate)
969                                 userInfo:nil
970                                 repeats:YES] retain];
971         [self timerUpdate];
972         ITDebugLog(@"Connection successful.");
973         return 1;
974     } else if (result == 0) {
975         ITDebugLog(@"Connection failed.");
976         currentRemote = [remoteArray objectAtIndex:0];
977         return 0;
978     } else {
979         //Do something about the password being invalid
980         ITDebugLog(@"Connection failed.");
981         currentRemote = [remoteArray objectAtIndex:0];
982         return -1;
983     }
984 }
985
986 - (BOOL)disconnectFromServer
987 {
988     ITDebugLog(@"Disconnecting from shared remote.");
989     //Disconnect
990     [currentRemote release];
991     currentRemote = [remoteArray objectAtIndex:0];
992     [networkController disconnect];
993     [self timerUpdate];
994     return YES;
995 }
996
997 - (void)checkForRemoteServer:(NSTimer *)timer
998 {
999     ITDebugLog(@"Checking for remote server.");
1000     if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1001         ITDebugLog(@"Remote server found.");
1002         [timer invalidate];
1003         if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1004             [[StatusWindowController sharedController] showReconnectQueryWindow];
1005         }
1006     } else {
1007         ITDebugLog(@"Remote server not found.");
1008     }
1009 }
1010
1011 - (void)networkError:(NSException *)exception
1012 {
1013     ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1014     NSLog(@"%@", [exception reason]);
1015     if ([[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