Added a "CustomPlayerPath" option for those with Classic iTunes problems.
[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         
309         if ([df boolForKey:@"runScripts"] && [[self currentRemote] currentSongTitle]) {
310             NSArray *scripts = [[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"]];
311             NSEnumerator *scriptsEnum = [scripts objectEnumerator];
312             NSString *nextScript;
313             while ( (nextScript = [scriptsEnum nextObject]) ) {
314                 NSDictionary *error;
315                 NSAppleScript *currentScript = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"] stringByAppendingPathComponent:nextScript]] error:&error];
316                 if (!currentScript || ![currentScript executeAndReturnError:nil]) {
317                     ITDebugLog(@"Error running script %@.", nextScript);
318                 }
319                 [currentScript release];
320             }
321         }
322         
323         timerUpdating = YES;
324         
325         NS_DURING
326             latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
327             [menuController rebuildSubmenus];
328     
329             if ( [df boolForKey:@"showSongInfoOnChange"] ) {
330                 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
331             }
332             
333             [self setLatestSongIdentifier:[[self currentRemote] playerStateUniqueIdentifier]];
334             
335             NSString *artist = [[self currentRemote] currentSongArtist];
336             NSString *title = [[self currentRemote] currentSongTitle];
337             NSString *toolTip;
338             if (artist) {
339                 toolTip = [NSString stringWithFormat:@"%@ - %@", artist, title];
340             } else if (title) {
341                 toolTip = title;
342             } else {
343                 toolTip = @"No Song Playing";
344             }
345             [statusItem setToolTip:toolTip];
346         NS_HANDLER
347             [self networkError:localException];
348         NS_ENDHANDLER
349         
350         timerUpdating = NO;
351     }
352 }
353
354 - (void)menuClicked
355 {
356     ITDebugLog(@"Menu clicked.");
357     if ([networkController isConnectedToServer]) {
358         //Used the cached version
359         return;
360     }
361     
362     NS_DURING
363         if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
364             [statusItem setMenu:[menuController menu]];
365         } else {
366             [statusItem setMenu:[menuController menuForNoPlayer]];
367         }
368     NS_HANDLER
369         [self networkError:localException];
370     NS_ENDHANDLER
371 }
372
373 //
374 //
375 // Menu Selectors
376 //
377 //
378
379 - (void)playPause
380 {
381     NS_DURING
382         ITMTRemotePlayerPlayingState state = [[self currentRemote] playerPlayingState];
383         ITDebugLog(@"Play/Pause toggled");
384         if (state == ITMTRemotePlayerPlaying) {
385             [[self currentRemote] pause];
386         } else if ((state == ITMTRemotePlayerForwarding) || (state == ITMTRemotePlayerRewinding)) {
387             [[self currentRemote] pause];
388             [[self currentRemote] play];
389         } else {
390             [[self currentRemote] play];
391         }
392     NS_HANDLER
393         [self networkError:localException];
394     NS_ENDHANDLER
395     
396     [self timerUpdate];
397 }
398
399 - (void)nextSong
400 {
401     ITDebugLog(@"Going to next song.");
402     NS_DURING
403         [[self currentRemote] goToNextSong];
404     NS_HANDLER
405         [self networkError:localException];
406     NS_ENDHANDLER
407     [self timerUpdate];
408 }
409
410 - (void)prevSong
411 {
412     ITDebugLog(@"Going to previous song.");
413     NS_DURING
414         [[self currentRemote] goToPreviousSong];
415     NS_HANDLER
416         [self networkError:localException];
417     NS_ENDHANDLER
418     [self timerUpdate];
419 }
420
421 - (void)fastForward
422 {
423     ITDebugLog(@"Fast forwarding.");
424     NS_DURING
425         [[self currentRemote] forward];
426     NS_HANDLER
427         [self networkError:localException];
428     NS_ENDHANDLER
429     [self timerUpdate];
430 }
431
432 - (void)rewind
433 {
434     ITDebugLog(@"Rewinding.");
435     NS_DURING
436         [[self currentRemote] rewind];
437     NS_HANDLER
438         [self networkError:localException];
439     NS_ENDHANDLER
440     [self timerUpdate];
441 }
442
443 - (void)selectPlaylistAtIndex:(int)index
444 {
445     ITDebugLog(@"Selecting playlist %i", index);
446     NS_DURING
447         [[self currentRemote] switchToPlaylistAtIndex:(index % 1000) ofSourceAtIndex:(index / 1000)];
448         //[[self currentRemote] switchToPlaylistAtIndex:index];
449     NS_HANDLER
450         [self networkError:localException];
451     NS_ENDHANDLER
452     [self timerUpdate];
453 }
454
455 - (void)selectSongAtIndex:(int)index
456 {
457     ITDebugLog(@"Selecting song %i", index);
458     NS_DURING
459         [[self currentRemote] switchToSongAtIndex:index];
460     NS_HANDLER
461         [self networkError:localException];
462     NS_ENDHANDLER
463     [self timerUpdate];
464 }
465
466 - (void)selectSongRating:(int)rating
467 {
468     ITDebugLog(@"Selecting song rating %i", rating);
469     NS_DURING
470         [[self currentRemote] setCurrentSongRating:(float)rating / 100.0];
471     NS_HANDLER
472         [self networkError:localException];
473     NS_ENDHANDLER
474     [self timerUpdate];
475 }
476
477 - (void)selectEQPresetAtIndex:(int)index
478 {
479     ITDebugLog(@"Selecting EQ preset %i", index);
480     NS_DURING
481         [[self currentRemote] switchToEQAtIndex:index];
482     NS_HANDLER
483         [self networkError:localException];
484     NS_ENDHANDLER
485     [self timerUpdate];
486 }
487
488 - (void)showPlayer
489 {
490     ITDebugLog(@"Beginning show player.");
491     if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
492         ITDebugLog(@"Showing player interface.");
493         NS_DURING
494             [[self currentRemote] showPrimaryInterface];
495         NS_HANDLER
496             [self networkError:localException];
497         NS_ENDHANDLER
498     } else {
499         ITDebugLog(@"Launching player.");
500         NS_DURING
501             NSString *path;
502             if ( (path = [df stringForKey:@"CustomPlayerPath"]) ) {
503             } else {
504                 path = [[self currentRemote] playerFullName];
505             }
506             if (![[NSWorkspace sharedWorkspace] launchApplication:path]) {
507                 ITDebugLog(@"Error Launching Player");
508             }
509         NS_HANDLER
510             [self networkError:localException];
511         NS_ENDHANDLER
512     }
513     ITDebugLog(@"Finished show player.");
514 }
515
516 - (void)showPreferences
517 {
518     ITDebugLog(@"Show preferences.");
519     [[PreferencesController sharedPrefs] showPrefsWindow:self];
520 }
521
522 - (void)showPreferencesAndClose
523 {
524     ITDebugLog(@"Show preferences.");
525     [[PreferencesController sharedPrefs] showPrefsWindow:self];
526     [[StatusWindow sharedWindow] setLocked:NO];
527     [[StatusWindow sharedWindow] vanish:self];
528     [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
529 }
530
531 - (void)showTestWindow
532 {
533     [self showCurrentTrackInfo];
534 }
535
536 - (void)quitMenuTunes
537 {
538     ITDebugLog(@"Quitting MenuTunes.");
539     [NSApp terminate:self];
540 }
541
542 //
543 //
544
545 - (void)closePreferences
546 {
547     ITDebugLog(@"Preferences closed.");
548     if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
549         [self setupHotKeys];
550     }
551 }
552
553 - (ITMTRemote *)currentRemote
554 {
555     if ([networkController isConnectedToServer] && ![[networkController networkObject] isValid]) {
556         [self networkError:nil];
557         return nil;
558     }
559     return currentRemote;
560 }
561
562 //
563 //
564 // Hot key setup
565 //
566 //
567
568 - (void)clearHotKeys
569 {
570     NSEnumerator *hotKeyEnumerator = [[[ITHotKeyCenter sharedCenter] allHotKeys] objectEnumerator];
571     ITHotKey *nextHotKey;
572     ITDebugLog(@"Clearing hot keys.");
573     while ( (nextHotKey = [hotKeyEnumerator nextObject]) ) {
574         [[ITHotKeyCenter sharedCenter] unregisterHotKey:nextHotKey];
575     }
576     ITDebugLog(@"Done clearing hot keys.");
577 }
578
579 - (void)setupHotKeys
580 {
581     ITHotKey *hotKey;
582     ITDebugLog(@"Setting up hot keys.");
583     
584     if (playerRunningState == ITMTRemotePlayerNotRunning) {
585         return;
586     }
587     
588     if ([df objectForKey:@"PlayPause"] != nil) {
589         ITDebugLog(@"Setting up play pause hot key.");
590         hotKey = [[ITHotKey alloc] init];
591         [hotKey setName:@"PlayPause"];
592         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PlayPause"]]];
593         [hotKey setTarget:self];
594         [hotKey setAction:@selector(playPause)];
595         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
596     }
597     
598     if ([df objectForKey:@"NextTrack"] != nil) {
599         ITDebugLog(@"Setting up next track hot key.");
600         hotKey = [[ITHotKey alloc] init];
601         [hotKey setName:@"NextTrack"];
602         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"NextTrack"]]];
603         [hotKey setTarget:self];
604         [hotKey setAction:@selector(nextSong)];
605         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
606     }
607     
608     if ([df objectForKey:@"PrevTrack"] != nil) {
609         ITDebugLog(@"Setting up previous track hot key.");
610         hotKey = [[ITHotKey alloc] init];
611         [hotKey setName:@"PrevTrack"];
612         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PrevTrack"]]];
613         [hotKey setTarget:self];
614         [hotKey setAction:@selector(prevSong)];
615         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
616     }
617     
618     if ([df objectForKey:@"ShowPlayer"] != nil) {
619         ITDebugLog(@"Setting up show player hot key.");
620         hotKey = [[ITHotKey alloc] init];
621         [hotKey setName:@"ShowPlayer"];
622         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
623         [hotKey setTarget:self];
624         [hotKey setAction:@selector(showPlayer)];
625         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
626     }
627     
628     if ([df objectForKey:@"TrackInfo"] != nil) {
629         ITDebugLog(@"Setting up track info hot key.");
630         hotKey = [[ITHotKey alloc] init];
631         [hotKey setName:@"TrackInfo"];
632         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"TrackInfo"]]];
633         [hotKey setTarget:self];
634         [hotKey setAction:@selector(showCurrentTrackInfo)];
635         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
636     }
637     
638     if ([df objectForKey:@"UpcomingSongs"] != nil) {
639         ITDebugLog(@"Setting up upcoming songs hot key.");
640         hotKey = [[ITHotKey alloc] init];
641         [hotKey setName:@"UpcomingSongs"];
642         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"UpcomingSongs"]]];
643         [hotKey setTarget:self];
644         [hotKey setAction:@selector(showUpcomingSongs)];
645         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
646     }
647     
648     if ([df objectForKey:@"ToggleLoop"] != nil) {
649         ITDebugLog(@"Setting up toggle loop hot key.");
650         hotKey = [[ITHotKey alloc] init];
651         [hotKey setName:@"ToggleLoop"];
652         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleLoop"]]];
653         [hotKey setTarget:self];
654         [hotKey setAction:@selector(toggleLoop)];
655         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
656     }
657     
658     if ([df objectForKey:@"ToggleShuffle"] != nil) {
659         ITDebugLog(@"Setting up toggle shuffle hot key.");
660         hotKey = [[ITHotKey alloc] init];
661         [hotKey setName:@"ToggleShuffle"];
662         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShuffle"]]];
663         [hotKey setTarget:self];
664         [hotKey setAction:@selector(toggleShuffle)];
665         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
666     }
667     
668     if ([df objectForKey:@"IncrementVolume"] != nil) {
669         ITDebugLog(@"Setting up increment volume hot key.");
670         hotKey = [[ITHotKey alloc] init];
671         [hotKey setName:@"IncrementVolume"];
672         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementVolume"]]];
673         [hotKey setTarget:self];
674         [hotKey setAction:@selector(incrementVolume)];
675         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
676     }
677     
678     if ([df objectForKey:@"DecrementVolume"] != nil) {
679         ITDebugLog(@"Setting up decrement volume hot key.");
680         hotKey = [[ITHotKey alloc] init];
681         [hotKey setName:@"DecrementVolume"];
682         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementVolume"]]];
683         [hotKey setTarget:self];
684         [hotKey setAction:@selector(decrementVolume)];
685         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
686     }
687     
688     if ([df objectForKey:@"IncrementRating"] != nil) {
689         ITDebugLog(@"Setting up increment rating hot key.");
690         hotKey = [[ITHotKey alloc] init];
691         [hotKey setName:@"IncrementRating"];
692         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementRating"]]];
693         [hotKey setTarget:self];
694         [hotKey setAction:@selector(incrementRating)];
695         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
696     }
697     
698     if ([df objectForKey:@"DecrementRating"] != nil) {
699         ITDebugLog(@"Setting up decrement rating hot key.");
700         hotKey = [[ITHotKey alloc] init];
701         [hotKey setName:@"DecrementRating"];
702         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementRating"]]];
703         [hotKey setTarget:self];
704         [hotKey setAction:@selector(decrementRating)];
705         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
706     }
707     ITDebugLog(@"Finished setting up hot keys.");
708 }
709
710 - (void)showCurrentTrackInfo
711 {
712     ITMTRemotePlayerSource  source      = 0;
713     NSString               *title       = nil;
714     NSString               *album       = nil;
715     NSString               *artist      = nil;
716     NSString               *time        = nil;
717     NSString               *track       = nil;
718     NSImage                *art         = nil;
719     int                     rating      = -1;
720     
721     NS_DURING
722         source      = [[self currentRemote] currentSource];
723         title       = [[self currentRemote] currentSongTitle];
724     NS_HANDLER
725         [self networkError:localException];
726     NS_ENDHANDLER
727     
728     ITDebugLog(@"Showing track info status window.");
729     
730     if ( title ) {
731
732         if ( [df boolForKey:@"showAlbum"] ) {
733             NS_DURING
734                 album = [[self currentRemote] currentSongAlbum];
735             NS_HANDLER
736                 [self networkError:localException];
737             NS_ENDHANDLER
738         }
739
740         if ( [df boolForKey:@"showArtist"] ) {
741             NS_DURING
742                 artist = [[self currentRemote] currentSongArtist];
743             NS_HANDLER
744                 [self networkError:localException];
745             NS_ENDHANDLER
746         }
747
748         if ( [df boolForKey:@"showTime"] ) {
749             NS_DURING
750                 time = [NSString stringWithFormat:@"%@: %@ / %@",
751                 @"Time",
752                 [[self currentRemote] currentSongElapsed],
753                 [[self currentRemote] currentSongLength]];
754             NS_HANDLER
755                 [self networkError:localException];
756             NS_ENDHANDLER
757         }
758
759         if ( [df boolForKey:@"showTrackNumber"] ) {
760             int trackNo    = 0;
761             int trackCount = 0;
762             
763             NS_DURING
764                 trackNo    = [[self currentRemote] currentSongTrack];
765                 trackCount = [[self currentRemote] currentAlbumTrackCount];
766             NS_HANDLER
767                 [self networkError:localException];
768             NS_ENDHANDLER
769             
770             if ( (trackNo > 0) || (trackCount > 0) ) {
771                 track = [NSString stringWithFormat:@"%@: %i %@ %i",
772                     @"Track", trackNo, @"of", trackCount];
773             }
774         }
775
776         if ( [df boolForKey:@"showTrackRating"] ) {
777             float currentRating = 0;
778             
779             NS_DURING
780                 currentRating = [[self currentRemote] currentSongRating];
781             NS_HANDLER
782                 [self networkError:localException];
783             NS_ENDHANDLER
784             
785             if (currentRating >= 0.0) {
786                 rating = ( currentRating * 5 );
787             }
788         }
789         
790         if ( [df boolForKey:@"showAlbumArtwork"] ) {
791              NS_DURING
792                 art = [[self currentRemote] currentSongAlbumArt];
793             NS_HANDLER
794                 [self networkError:localException];
795             NS_ENDHANDLER
796         }
797         
798     } else {
799         title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
800     }
801
802     [statusWindowController showSongInfoWindowWithSource:source
803                                                    title:title
804                                                    album:album
805                                                   artist:artist
806                                                     time:time
807                                                    track:track
808                                                   rating:rating
809                                                    image:art];
810 }
811
812 - (void)showUpcomingSongs
813 {
814     int numSongs = 0;
815     NS_DURING
816         numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
817     NS_HANDLER
818         [self networkError:localException];
819     NS_ENDHANDLER
820     
821     ITDebugLog(@"Showing upcoming songs status window.");
822     NS_DURING
823         if (numSongs > 0) {
824             int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
825             NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
826             int curTrack = [[self currentRemote] currentSongIndex];
827             int i;
828     
829             for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
830                 if (i <= numSongs) {
831                     [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
832                 }
833             }
834             
835             if ([songList count] == 0) {
836                 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
837             }
838             
839             [statusWindowController showUpcomingSongsWindowWithTitles:songList];
840         } else {
841             [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
842         }
843     NS_HANDLER
844         [self networkError:localException];
845     NS_ENDHANDLER
846 }
847
848 - (void)incrementVolume
849 {
850     NS_DURING
851         float volume  = [[self currentRemote] volume];
852         float dispVol = volume;
853         ITDebugLog(@"Incrementing volume.");
854         volume  += 0.110;
855         dispVol += 0.100;
856         
857         if (volume > 1.0) {
858             volume  = 1.0;
859             dispVol = 1.0;
860         }
861     
862         ITDebugLog(@"Setting volume to %f", volume);
863         [[self currentRemote] setVolume:volume];
864     
865         // Show volume status window
866         [statusWindowController showVolumeWindowWithLevel:dispVol];
867     NS_HANDLER
868         [self networkError:localException];
869     NS_ENDHANDLER
870 }
871
872 - (void)decrementVolume
873 {
874     NS_DURING
875         float volume  = [[self currentRemote] volume];
876         float dispVol = volume;
877         ITDebugLog(@"Decrementing volume.");
878         volume  -= 0.090;
879         dispVol -= 0.100;
880     
881         if (volume < 0.0) {
882             volume  = 0.0;
883             dispVol = 0.0;
884         }
885         
886         ITDebugLog(@"Setting volume to %f", volume);
887         [[self currentRemote] setVolume:volume];
888         
889         //Show volume status window
890         [statusWindowController showVolumeWindowWithLevel:dispVol];
891     NS_HANDLER
892         [self networkError:localException];
893     NS_ENDHANDLER
894 }
895
896 - (void)incrementRating
897 {
898     NS_DURING
899         float rating = [[self currentRemote] currentSongRating];
900         ITDebugLog(@"Incrementing rating.");
901         
902         if ([[self currentRemote] currentPlaylistIndex] == 0) {
903             ITDebugLog(@"No song playing, rating change aborted.");
904             return;
905         }
906         
907         rating += 0.2;
908         if (rating > 1.0) {
909             rating = 1.0;
910         }
911         ITDebugLog(@"Setting rating to %f", rating);
912         [[self currentRemote] setCurrentSongRating:rating];
913         
914         //Show rating status window
915         [statusWindowController showRatingWindowWithRating:rating];
916     NS_HANDLER
917         [self networkError:localException];
918     NS_ENDHANDLER
919 }
920
921 - (void)decrementRating
922 {
923     NS_DURING
924         float rating = [[self currentRemote] currentSongRating];
925         ITDebugLog(@"Decrementing rating.");
926         
927         if ([[self currentRemote] currentPlaylistIndex] == 0) {
928             ITDebugLog(@"No song playing, rating change aborted.");
929             return;
930         }
931         
932         rating -= 0.2;
933         if (rating < 0.0) {
934             rating = 0.0;
935         }
936         ITDebugLog(@"Setting rating to %f", rating);
937         [[self currentRemote] setCurrentSongRating:rating];
938         
939         //Show rating status window
940         [statusWindowController showRatingWindowWithRating:rating];
941     NS_HANDLER
942         [self networkError:localException];
943     NS_ENDHANDLER
944 }
945
946 - (void)toggleLoop
947 {
948     NS_DURING
949         ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
950         ITDebugLog(@"Toggling repeat mode.");
951         switch (repeatMode) {
952             case ITMTRemotePlayerRepeatOff:
953                 repeatMode = ITMTRemotePlayerRepeatAll;
954             break;
955             case ITMTRemotePlayerRepeatAll:
956                 repeatMode = ITMTRemotePlayerRepeatOne;
957             break;
958             case ITMTRemotePlayerRepeatOne:
959                 repeatMode = ITMTRemotePlayerRepeatOff;
960             break;
961         }
962         ITDebugLog(@"Setting repeat mode to %i", repeatMode);
963         [[self currentRemote] setRepeatMode:repeatMode];
964         
965         //Show loop status window
966         [statusWindowController showRepeatWindowWithMode:repeatMode];
967     NS_HANDLER
968         [self networkError:localException];
969     NS_ENDHANDLER
970 }
971
972 - (void)toggleShuffle
973 {
974     NS_DURING
975         BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
976         ITDebugLog(@"Toggling shuffle mode.");
977         [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
978         //Show shuffle status window
979         ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
980         [statusWindowController showShuffleWindow:newShuffleEnabled];
981     NS_HANDLER
982         [self networkError:localException];
983     NS_ENDHANDLER
984 }
985
986 - (void)registerNowOK
987 {
988     [[StatusWindow sharedWindow] setLocked:NO];
989     [[StatusWindow sharedWindow] vanish:self];
990     [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
991
992     [self blingNow];
993 }
994
995 - (void)registerNowCancel
996 {
997     [[StatusWindow sharedWindow] setLocked:NO];
998     [[StatusWindow sharedWindow] vanish:self];
999     [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1000
1001     [NSApp terminate:self];
1002 }
1003
1004 /*************************************************************************/
1005 #pragma mark -
1006 #pragma mark NETWORK HANDLERS
1007 /*************************************************************************/
1008
1009 - (void)setServerStatus:(BOOL)newStatus
1010 {
1011     if (newStatus) {
1012         //Turn on
1013         [networkController setServerStatus:YES];
1014     } else {
1015         //Tear down
1016         [networkController setServerStatus:NO];
1017     }
1018 }
1019
1020 - (int)connectToServer
1021 {
1022     int result;
1023     ITDebugLog(@"Attempting to connect to shared remote.");
1024     result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
1025     //Connect
1026     if (result == 1) {
1027         [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1028         currentRemote = [[[networkController networkObject] remote] retain];
1029         [refreshTimer invalidate];
1030         refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1031                                 target:self
1032                                 selector:@selector(timerUpdate)
1033                                 userInfo:nil
1034                                 repeats:YES] retain];
1035         [self timerUpdate];
1036         ITDebugLog(@"Connection successful.");
1037         return 1;
1038     } else if (result == 0) {
1039         ITDebugLog(@"Connection failed.");
1040         currentRemote = [remoteArray objectAtIndex:0];
1041         return 0;
1042     } else {
1043         //Do something about the password being invalid
1044         ITDebugLog(@"Connection failed.");
1045         currentRemote = [remoteArray objectAtIndex:0];
1046         return -1;
1047     }
1048 }
1049
1050 - (BOOL)disconnectFromServer
1051 {
1052     ITDebugLog(@"Disconnecting from shared remote.");
1053     //Disconnect
1054     [currentRemote release];
1055     currentRemote = [remoteArray objectAtIndex:0];
1056     [networkController disconnect];
1057     [self timerUpdate];
1058     return YES;
1059 }
1060
1061 - (void)checkForRemoteServer:(NSTimer *)timer
1062 {
1063     ITDebugLog(@"Checking for remote server.");
1064     if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1065         ITDebugLog(@"Remote server found.");
1066         [timer invalidate];
1067         if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1068             [[StatusWindowController sharedController] showReconnectQueryWindow];
1069         }
1070     } else {
1071         ITDebugLog(@"Remote server not found.");
1072     }
1073 }
1074
1075 - (void)networkError:(NSException *)exception
1076 {
1077     ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1078     if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1079         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);
1080         if ([self disconnectFromServer]) {
1081             [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1082             [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
1083         } else {
1084             ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1085         }
1086     }
1087 }
1088
1089 - (void)reconnect
1090 {
1091     if ([self connectToServer] == 0) {
1092         [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
1093     }
1094     [[StatusWindow sharedWindow] setLocked:NO];
1095     [[StatusWindow sharedWindow] vanish:self];
1096     [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1097 }
1098
1099 - (void)cancelReconnect
1100 {
1101     [[StatusWindow sharedWindow] setLocked:NO];
1102     [[StatusWindow sharedWindow] vanish:self];
1103     [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1104 }
1105
1106 /*************************************************************************/
1107 #pragma mark -
1108 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1109 /*************************************************************************/
1110
1111 - (void)applicationLaunched:(NSNotification *)note
1112 {
1113     NS_DURING
1114         if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]]) {
1115             ITDebugLog(@"Remote application launched.");
1116             playerRunningState = ITMTRemotePlayerRunning;
1117             [[self currentRemote] begin];
1118             [self setLatestSongIdentifier:@""];
1119             [self timerUpdate];
1120             refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1121                                 target:self
1122                                 selector:@selector(timerUpdate)
1123                                 userInfo:nil
1124                                 repeats:YES] retain];
1125             //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1126             [self setupHotKeys];
1127         }
1128     NS_HANDLER
1129         [self networkError:localException];
1130     NS_ENDHANDLER
1131 }
1132
1133  - (void)applicationTerminated:(NSNotification *)note
1134  {
1135     NS_DURING
1136         if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]]) {
1137             ITDebugLog(@"Remote application terminated.");
1138             playerRunningState = ITMTRemotePlayerNotRunning;
1139             [[self currentRemote] halt];
1140             [refreshTimer invalidate];
1141             [refreshTimer release];
1142             refreshTimer = nil;
1143             [self clearHotKeys];
1144             
1145             if ([df objectForKey:@"ShowPlayer"] != nil) {
1146                 ITHotKey *hotKey;
1147                 ITDebugLog(@"Setting up show player hot key.");
1148                 hotKey = [[ITHotKey alloc] init];
1149                 [hotKey setName:@"ShowPlayer"];
1150                 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1151                 [hotKey setTarget:self];
1152                 [hotKey setAction:@selector(showPlayer)];
1153                 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1154             }
1155         }
1156     NS_HANDLER
1157         [self networkError:localException];
1158     NS_ENDHANDLER
1159  }
1160
1161
1162 /*************************************************************************/
1163 #pragma mark -
1164 #pragma mark NSApplication DELEGATE METHODS
1165 /*************************************************************************/
1166
1167 - (void)applicationWillTerminate:(NSNotification *)note
1168 {
1169     [networkController stopRemoteServerSearch];
1170     [self clearHotKeys];
1171     [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1172 }
1173
1174
1175 /*************************************************************************/
1176 #pragma mark -
1177 #pragma mark DEALLOCATION METHOD
1178 /*************************************************************************/
1179
1180 - (void)dealloc
1181 {
1182     [self applicationTerminated:nil];
1183     [bling release];
1184     [statusItem release];
1185     [statusWindowController release];
1186     [menuController release];
1187     [networkController release];
1188     [super dealloc];
1189 }
1190
1191 @end