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