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