Fixed more bugs having to do with the updating of the prefs file to 1.2
[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     if (([df integerForKey:@"appVersion"] < 1200) && ([df integerForKey:@"SongsInAdvance"] > 0)) {
59         [df removePersistentDomainForName:@"com.ithinksw.menutunes"];
60         [df synchronize];
61         [[PreferencesController sharedPrefs] registerDefaults];
62         [[StatusWindowController sharedController] showPreferencesUpdateWindow];
63     }
64     
65     currentRemote = [self loadRemote];
66     [[self currentRemote] begin];
67     
68     //Turn on network stuff if needed
69     networkController = [[NetworkController alloc] init];
70     if ([df boolForKey:@"enableSharing"]) {
71         [self setServerStatus:YES];
72     } else if ([df boolForKey:@"useSharedPlayer"]) {
73         if ([self connectToServer] == 0) {
74             [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
75         }
76     }
77     
78     //Setup for notification of the remote player launching or quitting
79     [[[NSWorkspace sharedWorkspace] notificationCenter]
80             addObserver:self
81             selector:@selector(applicationTerminated:)
82             name:NSWorkspaceDidTerminateApplicationNotification
83             object:nil];
84     
85     [[[NSWorkspace sharedWorkspace] notificationCenter]
86             addObserver:self
87             selector:@selector(applicationLaunched:)
88             name:NSWorkspaceDidLaunchApplicationNotification
89             object:nil];
90     
91     if ( ! [df objectForKey:@"menu"] ) {  // If this is nil, defaults have never been registered.
92         [[PreferencesController sharedPrefs] registerDefaults];
93     }
94     
95     [StatusItemHack install];
96     statusItem = [[ITStatusItem alloc]
97             initWithStatusBar:[NSStatusBar systemStatusBar]
98             withLength:NSSquareStatusItemLength];
99     
100     bling = [[MTBlingController alloc] init];
101     [self blingTime];
102     registerTimer = [[NSTimer scheduledTimerWithTimeInterval:10.0
103                              target:self
104                              selector:@selector(blingTime)
105                              userInfo:nil
106                              repeats:YES] retain];
107     
108     NS_DURING
109         if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
110             [self applicationLaunched:nil];
111         } else {
112             if ([df boolForKey:@"LaunchPlayerWithMT"])
113                 [self showPlayer];
114             else
115                 [self applicationTerminated:nil];
116         }
117     NS_HANDLER
118         [self networkError:localException];
119     NS_ENDHANDLER
120     
121     [statusItem setImage:[NSImage imageNamed:@"MenuNormal"]];
122     [statusItem setAlternateImage:[NSImage imageNamed:@"MenuInverted"]];
123
124     [networkController startRemoteServerSearch];
125     [NSApp deactivate];
126 }
127
128 - (ITMTRemote *)loadRemote
129 {
130     NSString *folderPath = [[NSBundle mainBundle] builtInPlugInsPath];
131     ITDebugLog(@"Gathering remotes.");
132     if (folderPath) {
133         NSArray      *bundlePathList = [NSBundle pathsForResourcesOfType:@"remote" inDirectory:folderPath];
134         NSEnumerator *enumerator     = [bundlePathList objectEnumerator];
135         NSString     *bundlePath;
136
137         while ( (bundlePath = [enumerator nextObject]) ) {
138             NSBundle* remoteBundle = [NSBundle bundleWithPath:bundlePath];
139
140             if (remoteBundle) {
141                 Class remoteClass = [remoteBundle principalClass];
142
143                 if ([remoteClass conformsToProtocol:@protocol(ITMTRemote)] &&
144                     [remoteClass isKindOfClass:[NSObject class]]) {
145                     id remote = [remoteClass remote];
146                     ITDebugLog(@"Adding remote at path %@", bundlePath);
147                     [remoteArray addObject:remote];
148                 }
149             }
150         }
151
152 //      if ( [remoteArray count] > 0 ) {  // UNCOMMENT WHEN WE HAVE > 1 PLUGIN
153 //          if ( [remoteArray count] > 1 ) {
154 //              [remoteArray sortUsingSelector:@selector(sortAlpha:)];
155 //          }
156 //          [self loadModuleAccessUI]; //Comment out this line to disable remote visibility
157 //      }
158     }
159 //  NSLog(@"%@", [remoteArray objectAtIndex:0]);  //DEBUG
160     return [remoteArray objectAtIndex:0];
161 }
162
163 /*************************************************************************/
164 #pragma mark -
165 #pragma mark INSTANCE METHODS
166 /*************************************************************************/
167
168 /*- (void)startTimerInNewThread
169 {
170     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
171     NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
172     refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:0.5
173                              target:self
174                              selector:@selector(timerUpdate)
175                              userInfo:nil
176                              repeats:YES] retain];
177     [runLoop run];
178     ITDebugLog(@"Timer started.");
179     [pool release];
180 }*/
181
182 - (void)setBlingTime:(NSDate*)date
183 {
184     NSMutableDictionary *globalPrefs;
185     [df synchronize];
186     globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
187     if (date) {
188         [globalPrefs setObject:date forKey:@"ITMTTrialStart"];
189     } else {
190         [globalPrefs removeObjectForKey:@"ITMTTrialStart"];
191     }
192     [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
193     [df synchronize];
194     [globalPrefs release];
195 }
196
197 - (NSDate*)getBlingTime
198 {
199     [df synchronize];
200     return [[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialStart"];
201 }
202
203 - (void)blingTime
204 {
205     NSDate *now = [NSDate date];
206     if (![self blingBling]) {
207         if ( (! [self getBlingTime] ) || ([now timeIntervalSinceDate:[self getBlingTime]] < 0) ) {
208             [self setBlingTime:now];
209         }
210         if ( ([now timeIntervalSinceDate:[self getBlingTime]] >= 604800) && (blinged != YES) ) {
211             blinged = YES;
212             [statusItem setEnabled:NO];
213             [self clearHotKeys];
214             if ([refreshTimer isValid]) {
215                 [refreshTimer invalidate];
216             }
217             [statusWindowController showRegistrationQueryWindow];
218         }
219     } else {
220         if (blinged) {
221             [statusItem setEnabled:YES];
222             [self setupHotKeys];
223             if (![refreshTimer isValid]) {
224                 [refreshTimer release];
225                 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:0.5
226                              target:self
227                              selector:@selector(timerUpdate)
228                              userInfo:nil
229                              repeats:YES] retain];
230             }
231             blinged = NO;
232         }
233         [self setBlingTime:nil];
234     }
235 }
236
237 - (void)blingNow
238 {
239     [bling showPanel];
240 }
241
242 - (BOOL)blingBling
243 {
244     if ( ! ([bling checkDone] == 2475) ) {
245         return NO;
246     } else {
247         return YES;
248     }
249 }
250
251 - (BOOL)songIsPlaying
252 {
253     NSString *identifier = nil;
254     NS_DURING
255         identifier = [[self currentRemote] playerStateUniqueIdentifier];
256     NS_HANDLER
257         [self networkError:localException];
258     NS_ENDHANDLER
259     return ( ! ([identifier isEqualToString:@"0-0"]) );
260 }
261
262 - (BOOL)radioIsPlaying
263 {
264     ITMTRemotePlayerPlaylistClass class = nil;
265     NS_DURING
266         class = [[self currentRemote] currentPlaylistClass];
267     NS_HANDLER
268         [self networkError:localException];
269     NS_ENDHANDLER
270     return (class  == ITMTRemotePlayerRadioPlaylist );
271 }
272
273 - (BOOL)songChanged
274 {
275     NSString *identifier = nil;
276     NS_DURING
277         identifier = [[self currentRemote] playerStateUniqueIdentifier];
278     NS_HANDLER
279         [self networkError:localException];
280     NS_ENDHANDLER
281     return ( ! [identifier isEqualToString:_latestSongIdentifier] );
282 }
283
284 - (NSString *)latestSongIdentifier
285 {
286     return _latestSongIdentifier;
287 }
288
289 - (void)setLatestSongIdentifier:(NSString *)newIdentifier
290 {
291     ITDebugLog(@"Setting latest song identifier to %@", newIdentifier);
292     [_latestSongIdentifier autorelease];
293     _latestSongIdentifier = [newIdentifier copy];
294 }
295
296 - (void)timerUpdate
297 {
298     if ([networkController isConnectedToServer]) {
299         [statusItem setMenu:[menuController menu]];
300     }
301     
302     if ( [self songChanged] && (timerUpdating != YES) && (playerRunningState == ITMTRemotePlayerRunning) ) {
303         ITDebugLog(@"The song changed.");
304         timerUpdating = YES;
305         
306         NS_DURING
307             latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
308             [menuController rebuildSubmenus];
309     
310             if ( [df boolForKey:@"showSongInfoOnChange"] ) {
311                 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
312             }
313             
314             [self setLatestSongIdentifier:[[self currentRemote] playerStateUniqueIdentifier]];
315         NS_HANDLER
316             [self networkError:localException];
317         NS_ENDHANDLER
318         
319         timerUpdating = NO;
320     }
321 }
322
323 - (void)menuClicked
324 {
325     ITDebugLog(@"Menu clicked.");
326     if ([networkController isConnectedToServer]) {
327         //Used the cached version
328         return;
329     }
330     
331     NS_DURING
332         if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
333             [statusItem setMenu:[menuController menu]];
334         } else {
335             [statusItem setMenu:[menuController menuForNoPlayer]];
336         }
337     NS_HANDLER
338         [self networkError:localException];
339     NS_ENDHANDLER
340 }
341
342 //
343 //
344 // Menu Selectors
345 //
346 //
347
348 - (void)playPause
349 {
350     NS_DURING
351         ITMTRemotePlayerPlayingState state = [[self currentRemote] playerPlayingState];
352         ITDebugLog(@"Play/Pause toggled");
353         if (state == ITMTRemotePlayerPlaying) {
354             [[self currentRemote] pause];
355         } else if ((state == ITMTRemotePlayerForwarding) || (state == ITMTRemotePlayerRewinding)) {
356             [[self currentRemote] pause];
357             [[self currentRemote] play];
358         } else {
359             [[self currentRemote] play];
360         }
361     NS_HANDLER
362         [self networkError:localException];
363     NS_ENDHANDLER
364     
365     [self timerUpdate];
366 }
367
368 - (void)nextSong
369 {
370     ITDebugLog(@"Going to next song.");
371     NS_DURING
372         [[self currentRemote] goToNextSong];
373     NS_HANDLER
374         [self networkError:localException];
375     NS_ENDHANDLER
376     [self timerUpdate];
377 }
378
379 - (void)prevSong
380 {
381     ITDebugLog(@"Going to previous song.");
382     NS_DURING
383         [[self currentRemote] goToPreviousSong];
384     NS_HANDLER
385         [self networkError:localException];
386     NS_ENDHANDLER
387     [self timerUpdate];
388 }
389
390 - (void)fastForward
391 {
392     ITDebugLog(@"Fast forwarding.");
393     NS_DURING
394         [[self currentRemote] forward];
395     NS_HANDLER
396         [self networkError:localException];
397     NS_ENDHANDLER
398     [self timerUpdate];
399 }
400
401 - (void)rewind
402 {
403     ITDebugLog(@"Rewinding.");
404     NS_DURING
405         [[self currentRemote] rewind];
406     NS_HANDLER
407         [self networkError:localException];
408     NS_ENDHANDLER
409     [self timerUpdate];
410 }
411
412 - (void)selectPlaylistAtIndex:(int)index
413 {
414     ITDebugLog(@"Selecting playlist %i", index);
415     NS_DURING
416         //[[self currentRemote] switchToPlaylistAtIndex:(index % 1000) ofSourceAtIndex:(index / 1000)];
417         [[self currentRemote] switchToPlaylistAtIndex:index];
418     NS_HANDLER
419         [self networkError:localException];
420     NS_ENDHANDLER
421     [self timerUpdate];
422 }
423
424 - (void)selectSongAtIndex:(int)index
425 {
426     ITDebugLog(@"Selecting song %i", index);
427     NS_DURING
428         [[self currentRemote] switchToSongAtIndex:index];
429     NS_HANDLER
430         [self networkError:localException];
431     NS_ENDHANDLER
432     [self timerUpdate];
433 }
434
435 - (void)selectSongRating:(int)rating
436 {
437     ITDebugLog(@"Selecting song rating %i", rating);
438     NS_DURING
439         [[self currentRemote] setCurrentSongRating:(float)rating / 100.0];
440     NS_HANDLER
441         [self networkError:localException];
442     NS_ENDHANDLER
443     [self timerUpdate];
444 }
445
446 - (void)selectEQPresetAtIndex:(int)index
447 {
448     ITDebugLog(@"Selecting EQ preset %i", index);
449     NS_DURING
450         [[self currentRemote] switchToEQAtIndex:index];
451     NS_HANDLER
452         [self networkError:localException];
453     NS_ENDHANDLER
454     [self timerUpdate];
455 }
456
457 - (void)showPlayer
458 {
459     ITDebugLog(@"Beginning show player.");
460     if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
461         ITDebugLog(@"Showing player interface.");
462         NS_DURING
463             [[self currentRemote] showPrimaryInterface];
464         NS_HANDLER
465             [self networkError:localException];
466         NS_ENDHANDLER
467     } else {
468         ITDebugLog(@"Launching player.");
469         NS_DURING
470             if (![[NSWorkspace sharedWorkspace] launchApplication:[[self currentRemote] playerFullName]]) {
471                 ITDebugLog(@"Error Launching Player");
472             }
473         NS_HANDLER
474             [self networkError:localException];
475         NS_ENDHANDLER
476     }
477     ITDebugLog(@"Finished show player.");
478 }
479
480 - (void)showPreferences
481 {
482     ITDebugLog(@"Show preferences.");
483     [[PreferencesController sharedPrefs] showPrefsWindow:self];
484 }
485
486 - (void)showPreferencesAndClose
487 {
488     ITDebugLog(@"Show preferences.");
489     [[PreferencesController sharedPrefs] showPrefsWindow:self];
490     [[StatusWindow sharedWindow] setLocked:NO];
491     [[StatusWindow sharedWindow] vanish:self];
492     [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
493 }
494
495 - (void)showTestWindow
496 {
497     [self showCurrentTrackInfo];
498 }
499
500 - (void)quitMenuTunes
501 {
502     ITDebugLog(@"Quitting MenuTunes.");
503     [NSApp terminate:self];
504 }
505
506 //
507 //
508
509 - (void)closePreferences
510 {
511     ITDebugLog(@"Preferences closed.");
512     if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
513         [self setupHotKeys];
514     }
515 }
516
517 - (ITMTRemote *)currentRemote
518 {
519     if ([networkController isConnectedToServer] && ![[networkController networkObject] isValid]) {
520         [self networkError:nil];
521         return nil;
522     }
523     return currentRemote;
524 }
525
526 //
527 //
528 // Hot key setup
529 //
530 //
531
532 - (void)clearHotKeys
533 {
534     NSEnumerator *hotKeyEnumerator = [[[ITHotKeyCenter sharedCenter] allHotKeys] objectEnumerator];
535     ITHotKey *nextHotKey;
536     ITDebugLog(@"Clearing hot keys.");
537     while ( (nextHotKey = [hotKeyEnumerator nextObject]) ) {
538         [[ITHotKeyCenter sharedCenter] unregisterHotKey:nextHotKey];
539     }
540     ITDebugLog(@"Done clearing hot keys.");
541 }
542
543 - (void)setupHotKeys
544 {
545     ITHotKey *hotKey;
546     ITDebugLog(@"Setting up hot keys.");
547     
548     if (playerRunningState == ITMTRemotePlayerNotRunning) {
549         return;
550     }
551     
552     if ([df objectForKey:@"PlayPause"] != nil) {
553         ITDebugLog(@"Setting up play pause hot key.");
554         hotKey = [[ITHotKey alloc] init];
555         [hotKey setName:@"PlayPause"];
556         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PlayPause"]]];
557         [hotKey setTarget:self];
558         [hotKey setAction:@selector(playPause)];
559         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
560     }
561     
562     if ([df objectForKey:@"NextTrack"] != nil) {
563         ITDebugLog(@"Setting up next track hot key.");
564         hotKey = [[ITHotKey alloc] init];
565         [hotKey setName:@"NextTrack"];
566         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"NextTrack"]]];
567         [hotKey setTarget:self];
568         [hotKey setAction:@selector(nextSong)];
569         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
570     }
571     
572     if ([df objectForKey:@"PrevTrack"] != nil) {
573         ITDebugLog(@"Setting up previous track hot key.");
574         hotKey = [[ITHotKey alloc] init];
575         [hotKey setName:@"PrevTrack"];
576         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PrevTrack"]]];
577         [hotKey setTarget:self];
578         [hotKey setAction:@selector(prevSong)];
579         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
580     }
581     
582     if ([df objectForKey:@"ShowPlayer"] != nil) {
583         ITDebugLog(@"Setting up show player hot key.");
584         hotKey = [[ITHotKey alloc] init];
585         [hotKey setName:@"ShowPlayer"];
586         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
587         [hotKey setTarget:self];
588         [hotKey setAction:@selector(showPlayer)];
589         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
590     }
591     
592     if ([df objectForKey:@"TrackInfo"] != nil) {
593         ITDebugLog(@"Setting up track info hot key.");
594         hotKey = [[ITHotKey alloc] init];
595         [hotKey setName:@"TrackInfo"];
596         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"TrackInfo"]]];
597         [hotKey setTarget:self];
598         [hotKey setAction:@selector(showCurrentTrackInfo)];
599         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
600     }
601     
602     if ([df objectForKey:@"UpcomingSongs"] != nil) {
603         ITDebugLog(@"Setting up upcoming songs hot key.");
604         hotKey = [[ITHotKey alloc] init];
605         [hotKey setName:@"UpcomingSongs"];
606         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"UpcomingSongs"]]];
607         [hotKey setTarget:self];
608         [hotKey setAction:@selector(showUpcomingSongs)];
609         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
610     }
611     
612     if ([df objectForKey:@"ToggleLoop"] != nil) {
613         ITDebugLog(@"Setting up toggle loop hot key.");
614         hotKey = [[ITHotKey alloc] init];
615         [hotKey setName:@"ToggleLoop"];
616         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleLoop"]]];
617         [hotKey setTarget:self];
618         [hotKey setAction:@selector(toggleLoop)];
619         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
620     }
621     
622     if ([df objectForKey:@"ToggleShuffle"] != nil) {
623         ITDebugLog(@"Setting up toggle shuffle hot key.");
624         hotKey = [[ITHotKey alloc] init];
625         [hotKey setName:@"ToggleShuffle"];
626         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShuffle"]]];
627         [hotKey setTarget:self];
628         [hotKey setAction:@selector(toggleShuffle)];
629         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
630     }
631     
632     if ([df objectForKey:@"IncrementVolume"] != nil) {
633         ITDebugLog(@"Setting up increment volume hot key.");
634         hotKey = [[ITHotKey alloc] init];
635         [hotKey setName:@"IncrementVolume"];
636         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementVolume"]]];
637         [hotKey setTarget:self];
638         [hotKey setAction:@selector(incrementVolume)];
639         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
640     }
641     
642     if ([df objectForKey:@"DecrementVolume"] != nil) {
643         ITDebugLog(@"Setting up decrement volume hot key.");
644         hotKey = [[ITHotKey alloc] init];
645         [hotKey setName:@"DecrementVolume"];
646         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementVolume"]]];
647         [hotKey setTarget:self];
648         [hotKey setAction:@selector(decrementVolume)];
649         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
650     }
651     
652     if ([df objectForKey:@"IncrementRating"] != nil) {
653         ITDebugLog(@"Setting up increment rating hot key.");
654         hotKey = [[ITHotKey alloc] init];
655         [hotKey setName:@"IncrementRating"];
656         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementRating"]]];
657         [hotKey setTarget:self];
658         [hotKey setAction:@selector(incrementRating)];
659         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
660     }
661     
662     if ([df objectForKey:@"DecrementRating"] != nil) {
663         ITDebugLog(@"Setting up decrement rating hot key.");
664         hotKey = [[ITHotKey alloc] init];
665         [hotKey setName:@"DecrementRating"];
666         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementRating"]]];
667         [hotKey setTarget:self];
668         [hotKey setAction:@selector(decrementRating)];
669         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
670     }
671     ITDebugLog(@"Finished setting up hot keys.");
672 }
673
674 - (void)showCurrentTrackInfo
675 {
676     ITMTRemotePlayerSource  source      = 0;
677     NSString               *title       = nil;
678     NSString               *album       = nil;
679     NSString               *artist      = nil;
680     NSString               *time        = nil;
681     NSString               *track       = nil;
682     int                     rating      = -1;
683     
684     NS_DURING
685         source      = [[self currentRemote] currentSource];
686         title       = [[self currentRemote] currentSongTitle];
687     NS_HANDLER
688         [self networkError:localException];
689     NS_ENDHANDLER
690     
691     ITDebugLog(@"Showing track info status window.");
692     
693     if ( title ) {
694
695         if ( [df boolForKey:@"showAlbum"] ) {
696             NS_DURING
697                 album = [[self currentRemote] currentSongAlbum];
698             NS_HANDLER
699                 [self networkError:localException];
700             NS_ENDHANDLER
701         }
702
703         if ( [df boolForKey:@"showArtist"] ) {
704             NS_DURING
705                 artist = [[self currentRemote] currentSongArtist];
706             NS_HANDLER
707                 [self networkError:localException];
708             NS_ENDHANDLER
709         }
710
711         if ( [df boolForKey:@"showTime"] ) {
712             NS_DURING
713                 time = [NSString stringWithFormat:@"%@: %@ / %@",
714                 @"Time",
715                 [[self currentRemote] currentSongElapsed],
716                 [[self currentRemote] currentSongLength]];
717             NS_HANDLER
718                 [self networkError:localException];
719             NS_ENDHANDLER
720         }
721
722         if ( [df boolForKey:@"showTrackNumber"] ) {
723             int trackNo    = 0;
724             int trackCount = 0;
725             
726             NS_DURING
727                 trackNo    = [[self currentRemote] currentSongTrack];
728                 trackCount = [[self currentRemote] currentAlbumTrackCount];
729             NS_HANDLER
730                 [self networkError:localException];
731             NS_ENDHANDLER
732             
733             if ( (trackNo > 0) || (trackCount > 0) ) {
734                 track = [NSString stringWithFormat:@"%@: %i %@ %i",
735                     @"Track", trackNo, @"of", trackCount];
736             }
737         }
738
739         if ( [df boolForKey:@"showTrackRating"] ) {
740             float currentRating = 0;
741             
742             NS_DURING
743                 currentRating = [[self currentRemote] currentSongRating];
744             NS_HANDLER
745                 [self networkError:localException];
746             NS_ENDHANDLER
747             
748             if (currentRating >= 0.0) {
749                 rating = ( currentRating * 5 );
750             }
751         }
752         
753     } else {
754         title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
755     }
756
757     [statusWindowController showSongInfoWindowWithSource:source
758                                                    title:title
759                                                    album:album
760                                                   artist:artist
761                                                     time:time
762                                                    track:track
763                                                   rating:rating];
764 }
765
766 - (void)showUpcomingSongs
767 {
768     int numSongs = 0;
769     NS_DURING
770         numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
771     NS_HANDLER
772         [self networkError:localException];
773     NS_ENDHANDLER
774     
775     ITDebugLog(@"Showing upcoming songs status window.");
776     NS_DURING
777         if (numSongs > 0) {
778             int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
779             NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
780             int curTrack = [[self currentRemote] currentSongIndex];
781             int i;
782     
783             for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
784                 if (i <= numSongs) {
785                     [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
786                 }
787             }
788             
789             if ([songList count] == 0) {
790                 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
791             }
792             
793             [statusWindowController showUpcomingSongsWindowWithTitles:songList];
794         } else {
795             [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
796         }
797     NS_HANDLER
798         [self networkError:localException];
799     NS_ENDHANDLER
800 }
801
802 - (void)incrementVolume
803 {
804     NS_DURING
805         float volume  = [[self currentRemote] volume];
806         float dispVol = volume;
807         ITDebugLog(@"Incrementing volume.");
808         volume  += 0.110;
809         dispVol += 0.100;
810         
811         if (volume > 1.0) {
812             volume  = 1.0;
813             dispVol = 1.0;
814         }
815     
816         ITDebugLog(@"Setting volume to %f", volume);
817         [[self currentRemote] setVolume:volume];
818     
819         // Show volume status window
820         [statusWindowController showVolumeWindowWithLevel:dispVol];
821     NS_HANDLER
822         [self networkError:localException];
823     NS_ENDHANDLER
824 }
825
826 - (void)decrementVolume
827 {
828     NS_DURING
829         float volume  = [[self currentRemote] volume];
830         float dispVol = volume;
831         ITDebugLog(@"Decrementing volume.");
832         volume  -= 0.090;
833         dispVol -= 0.100;
834     
835         if (volume < 0.0) {
836             volume  = 0.0;
837             dispVol = 0.0;
838         }
839         
840         ITDebugLog(@"Setting volume to %f", volume);
841         [[self currentRemote] setVolume:volume];
842         
843         //Show volume status window
844         [statusWindowController showVolumeWindowWithLevel:dispVol];
845     NS_HANDLER
846         [self networkError:localException];
847     NS_ENDHANDLER
848 }
849
850 - (void)incrementRating
851 {
852     NS_DURING
853         float rating = [[self currentRemote] currentSongRating];
854         ITDebugLog(@"Incrementing rating.");
855         
856         if ([[self currentRemote] currentPlaylistIndex] == 0) {
857             ITDebugLog(@"No song playing, rating change aborted.");
858             return;
859         }
860         
861         rating += 0.2;
862         if (rating > 1.0) {
863             rating = 1.0;
864         }
865         ITDebugLog(@"Setting rating to %f", rating);
866         [[self currentRemote] setCurrentSongRating:rating];
867         
868         //Show rating status window
869         [statusWindowController showRatingWindowWithRating:rating];
870     NS_HANDLER
871         [self networkError:localException];
872     NS_ENDHANDLER
873 }
874
875 - (void)decrementRating
876 {
877     NS_DURING
878         float rating = [[self currentRemote] currentSongRating];
879         ITDebugLog(@"Decrementing rating.");
880         
881         if ([[self currentRemote] currentPlaylistIndex] == 0) {
882             ITDebugLog(@"No song playing, rating change aborted.");
883             return;
884         }
885         
886         rating -= 0.2;
887         if (rating < 0.0) {
888             rating = 0.0;
889         }
890         ITDebugLog(@"Setting rating to %f", rating);
891         [[self currentRemote] setCurrentSongRating:rating];
892         
893         //Show rating status window
894         [statusWindowController showRatingWindowWithRating:rating];
895     NS_HANDLER
896         [self networkError:localException];
897     NS_ENDHANDLER
898 }
899
900 - (void)toggleLoop
901 {
902     NS_DURING
903         ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
904         ITDebugLog(@"Toggling repeat mode.");
905         switch (repeatMode) {
906             case ITMTRemotePlayerRepeatOff:
907                 repeatMode = ITMTRemotePlayerRepeatAll;
908             break;
909             case ITMTRemotePlayerRepeatAll:
910                 repeatMode = ITMTRemotePlayerRepeatOne;
911             break;
912             case ITMTRemotePlayerRepeatOne:
913                 repeatMode = ITMTRemotePlayerRepeatOff;
914             break;
915         }
916         ITDebugLog(@"Setting repeat mode to %i", repeatMode);
917         [[self currentRemote] setRepeatMode:repeatMode];
918         
919         //Show loop status window
920         [statusWindowController showRepeatWindowWithMode:repeatMode];
921     NS_HANDLER
922         [self networkError:localException];
923     NS_ENDHANDLER
924 }
925
926 - (void)toggleShuffle
927 {
928     NS_DURING
929         BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
930         ITDebugLog(@"Toggling shuffle mode.");
931         [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
932         //Show shuffle status window
933         ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
934         [statusWindowController showShuffleWindow:newShuffleEnabled];
935     NS_HANDLER
936         [self networkError:localException];
937     NS_ENDHANDLER
938 }
939
940 - (void)registerNowOK
941 {
942     [[StatusWindow sharedWindow] setLocked:NO];
943     [[StatusWindow sharedWindow] vanish:self];
944     [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
945
946     [self blingNow];
947 }
948
949 - (void)registerNowCancel
950 {
951     [[StatusWindow sharedWindow] setLocked:NO];
952     [[StatusWindow sharedWindow] vanish:self];
953     [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
954
955     [NSApp terminate:self];
956 }
957
958 /*************************************************************************/
959 #pragma mark -
960 #pragma mark NETWORK HANDLERS
961 /*************************************************************************/
962
963 - (void)setServerStatus:(BOOL)newStatus
964 {
965     if (newStatus) {
966         //Turn on
967         [networkController setServerStatus:YES];
968     } else {
969         //Tear down
970         [networkController setServerStatus:NO];
971     }
972 }
973
974 - (int)connectToServer
975 {
976     int result;
977     ITDebugLog(@"Attempting to connect to shared remote.");
978     result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
979     //Connect
980     if (result == 1) {
981         [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
982         currentRemote = [[[networkController networkObject] remote] retain];
983         [refreshTimer invalidate];
984         refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
985                                 target:self
986                                 selector:@selector(timerUpdate)
987                                 userInfo:nil
988                                 repeats:YES] retain];
989         [self timerUpdate];
990         ITDebugLog(@"Connection successful.");
991         return 1;
992     } else if (result == 0) {
993         ITDebugLog(@"Connection failed.");
994         currentRemote = [remoteArray objectAtIndex:0];
995         return 0;
996     } else {
997         //Do something about the password being invalid
998         ITDebugLog(@"Connection failed.");
999         currentRemote = [remoteArray objectAtIndex:0];
1000         return -1;
1001     }
1002 }
1003
1004 - (BOOL)disconnectFromServer
1005 {
1006     ITDebugLog(@"Disconnecting from shared remote.");
1007     //Disconnect
1008     [currentRemote release];
1009     currentRemote = [remoteArray objectAtIndex:0];
1010     [networkController disconnect];
1011     [self timerUpdate];
1012     return YES;
1013 }
1014
1015 - (void)checkForRemoteServer:(NSTimer *)timer
1016 {
1017     ITDebugLog(@"Checking for remote server.");
1018     if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1019         ITDebugLog(@"Remote server found.");
1020         [timer invalidate];
1021         if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1022             [[StatusWindowController sharedController] showReconnectQueryWindow];
1023         }
1024     } else {
1025         ITDebugLog(@"Remote server not found.");
1026     }
1027 }
1028
1029 - (void)networkError:(NSException *)exception
1030 {
1031     ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1032     if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1033         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);
1034         if ([self disconnectFromServer]) {
1035             [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1036             [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
1037         } else {
1038             ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1039         }
1040     }
1041 }
1042
1043 - (void)reconnect
1044 {
1045     if ([self connectToServer] == 0) {
1046         [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
1047     }
1048     [[StatusWindow sharedWindow] setLocked:NO];
1049     [[StatusWindow sharedWindow] vanish:self];
1050     [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1051 }
1052
1053 - (void)cancelReconnect
1054 {
1055     [[StatusWindow sharedWindow] setLocked:NO];
1056     [[StatusWindow sharedWindow] vanish:self];
1057     [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1058 }
1059
1060 /*************************************************************************/
1061 #pragma mark -
1062 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1063 /*************************************************************************/
1064
1065 - (void)applicationLaunched:(NSNotification *)note
1066 {
1067     NS_DURING
1068         if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]]) {
1069             ITDebugLog(@"Remote application launched.");
1070             playerRunningState = ITMTRemotePlayerRunning;
1071             [[self currentRemote] begin];
1072             [self setLatestSongIdentifier:@""];
1073             [self timerUpdate];
1074             refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1075                                 target:self
1076                                 selector:@selector(timerUpdate)
1077                                 userInfo:nil
1078                                 repeats:YES] retain];
1079             //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1080             [self setupHotKeys];
1081         }
1082     NS_HANDLER
1083         [self networkError:localException];
1084     NS_ENDHANDLER
1085 }
1086
1087  - (void)applicationTerminated:(NSNotification *)note
1088  {
1089     NS_DURING
1090         if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]]) {
1091             ITDebugLog(@"Remote application terminated.");
1092             playerRunningState = ITMTRemotePlayerNotRunning;
1093             [[self currentRemote] halt];
1094             [refreshTimer invalidate];
1095             [refreshTimer release];
1096             refreshTimer = nil;
1097             [self clearHotKeys];
1098             
1099             if ([df objectForKey:@"ShowPlayer"] != nil) {
1100                 ITHotKey *hotKey;
1101                 ITDebugLog(@"Setting up show player hot key.");
1102                 hotKey = [[ITHotKey alloc] init];
1103                 [hotKey setName:@"ShowPlayer"];
1104                 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1105                 [hotKey setTarget:self];
1106                 [hotKey setAction:@selector(showPlayer)];
1107                 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1108             }
1109         }
1110     NS_HANDLER
1111         [self networkError:localException];
1112     NS_ENDHANDLER
1113  }
1114
1115
1116 /*************************************************************************/
1117 #pragma mark -
1118 #pragma mark NSApplication DELEGATE METHODS
1119 /*************************************************************************/
1120
1121 - (void)applicationWillTerminate:(NSNotification *)note
1122 {
1123     [networkController stopRemoteServerSearch];
1124     [self clearHotKeys];
1125     [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1126 }
1127
1128
1129 /*************************************************************************/
1130 #pragma mark -
1131 #pragma mark DEALLOCATION METHOD
1132 /*************************************************************************/
1133
1134 - (void)dealloc
1135 {
1136     [self applicationTerminated:nil];
1137     [bling release];
1138     [statusItem release];
1139     [statusWindowController release];
1140     [menuController release];
1141     [networkController release];
1142     [super dealloc];
1143 }
1144
1145 @end