Readding multisource playlist thingy. Added a tooltip showing the current
[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             if (![[NSWorkspace sharedWorkspace] launchApplication:[[self currentRemote] playerFullName]]) {
502                 ITDebugLog(@"Error Launching Player");
503             }
504         NS_HANDLER
505             [self networkError:localException];
506         NS_ENDHANDLER
507     }
508     ITDebugLog(@"Finished show player.");
509 }
510
511 - (void)showPreferences
512 {
513     ITDebugLog(@"Show preferences.");
514     [[PreferencesController sharedPrefs] showPrefsWindow:self];
515 }
516
517 - (void)showPreferencesAndClose
518 {
519     ITDebugLog(@"Show preferences.");
520     [[PreferencesController sharedPrefs] showPrefsWindow:self];
521     [[StatusWindow sharedWindow] setLocked:NO];
522     [[StatusWindow sharedWindow] vanish:self];
523     [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
524 }
525
526 - (void)showTestWindow
527 {
528     [self showCurrentTrackInfo];
529 }
530
531 - (void)quitMenuTunes
532 {
533     ITDebugLog(@"Quitting MenuTunes.");
534     [NSApp terminate:self];
535 }
536
537 //
538 //
539
540 - (void)closePreferences
541 {
542     ITDebugLog(@"Preferences closed.");
543     if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
544         [self setupHotKeys];
545     }
546 }
547
548 - (ITMTRemote *)currentRemote
549 {
550     if ([networkController isConnectedToServer] && ![[networkController networkObject] isValid]) {
551         [self networkError:nil];
552         return nil;
553     }
554     return currentRemote;
555 }
556
557 //
558 //
559 // Hot key setup
560 //
561 //
562
563 - (void)clearHotKeys
564 {
565     NSEnumerator *hotKeyEnumerator = [[[ITHotKeyCenter sharedCenter] allHotKeys] objectEnumerator];
566     ITHotKey *nextHotKey;
567     ITDebugLog(@"Clearing hot keys.");
568     while ( (nextHotKey = [hotKeyEnumerator nextObject]) ) {
569         [[ITHotKeyCenter sharedCenter] unregisterHotKey:nextHotKey];
570     }
571     ITDebugLog(@"Done clearing hot keys.");
572 }
573
574 - (void)setupHotKeys
575 {
576     ITHotKey *hotKey;
577     ITDebugLog(@"Setting up hot keys.");
578     
579     if (playerRunningState == ITMTRemotePlayerNotRunning) {
580         return;
581     }
582     
583     if ([df objectForKey:@"PlayPause"] != nil) {
584         ITDebugLog(@"Setting up play pause hot key.");
585         hotKey = [[ITHotKey alloc] init];
586         [hotKey setName:@"PlayPause"];
587         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PlayPause"]]];
588         [hotKey setTarget:self];
589         [hotKey setAction:@selector(playPause)];
590         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
591     }
592     
593     if ([df objectForKey:@"NextTrack"] != nil) {
594         ITDebugLog(@"Setting up next track hot key.");
595         hotKey = [[ITHotKey alloc] init];
596         [hotKey setName:@"NextTrack"];
597         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"NextTrack"]]];
598         [hotKey setTarget:self];
599         [hotKey setAction:@selector(nextSong)];
600         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
601     }
602     
603     if ([df objectForKey:@"PrevTrack"] != nil) {
604         ITDebugLog(@"Setting up previous track hot key.");
605         hotKey = [[ITHotKey alloc] init];
606         [hotKey setName:@"PrevTrack"];
607         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PrevTrack"]]];
608         [hotKey setTarget:self];
609         [hotKey setAction:@selector(prevSong)];
610         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
611     }
612     
613     if ([df objectForKey:@"ShowPlayer"] != nil) {
614         ITDebugLog(@"Setting up show player hot key.");
615         hotKey = [[ITHotKey alloc] init];
616         [hotKey setName:@"ShowPlayer"];
617         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
618         [hotKey setTarget:self];
619         [hotKey setAction:@selector(showPlayer)];
620         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
621     }
622     
623     if ([df objectForKey:@"TrackInfo"] != nil) {
624         ITDebugLog(@"Setting up track info hot key.");
625         hotKey = [[ITHotKey alloc] init];
626         [hotKey setName:@"TrackInfo"];
627         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"TrackInfo"]]];
628         [hotKey setTarget:self];
629         [hotKey setAction:@selector(showCurrentTrackInfo)];
630         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
631     }
632     
633     if ([df objectForKey:@"UpcomingSongs"] != nil) {
634         ITDebugLog(@"Setting up upcoming songs hot key.");
635         hotKey = [[ITHotKey alloc] init];
636         [hotKey setName:@"UpcomingSongs"];
637         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"UpcomingSongs"]]];
638         [hotKey setTarget:self];
639         [hotKey setAction:@selector(showUpcomingSongs)];
640         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
641     }
642     
643     if ([df objectForKey:@"ToggleLoop"] != nil) {
644         ITDebugLog(@"Setting up toggle loop hot key.");
645         hotKey = [[ITHotKey alloc] init];
646         [hotKey setName:@"ToggleLoop"];
647         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleLoop"]]];
648         [hotKey setTarget:self];
649         [hotKey setAction:@selector(toggleLoop)];
650         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
651     }
652     
653     if ([df objectForKey:@"ToggleShuffle"] != nil) {
654         ITDebugLog(@"Setting up toggle shuffle hot key.");
655         hotKey = [[ITHotKey alloc] init];
656         [hotKey setName:@"ToggleShuffle"];
657         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShuffle"]]];
658         [hotKey setTarget:self];
659         [hotKey setAction:@selector(toggleShuffle)];
660         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
661     }
662     
663     if ([df objectForKey:@"IncrementVolume"] != nil) {
664         ITDebugLog(@"Setting up increment volume hot key.");
665         hotKey = [[ITHotKey alloc] init];
666         [hotKey setName:@"IncrementVolume"];
667         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementVolume"]]];
668         [hotKey setTarget:self];
669         [hotKey setAction:@selector(incrementVolume)];
670         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
671     }
672     
673     if ([df objectForKey:@"DecrementVolume"] != nil) {
674         ITDebugLog(@"Setting up decrement volume hot key.");
675         hotKey = [[ITHotKey alloc] init];
676         [hotKey setName:@"DecrementVolume"];
677         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementVolume"]]];
678         [hotKey setTarget:self];
679         [hotKey setAction:@selector(decrementVolume)];
680         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
681     }
682     
683     if ([df objectForKey:@"IncrementRating"] != nil) {
684         ITDebugLog(@"Setting up increment rating hot key.");
685         hotKey = [[ITHotKey alloc] init];
686         [hotKey setName:@"IncrementRating"];
687         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementRating"]]];
688         [hotKey setTarget:self];
689         [hotKey setAction:@selector(incrementRating)];
690         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
691     }
692     
693     if ([df objectForKey:@"DecrementRating"] != nil) {
694         ITDebugLog(@"Setting up decrement rating hot key.");
695         hotKey = [[ITHotKey alloc] init];
696         [hotKey setName:@"DecrementRating"];
697         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementRating"]]];
698         [hotKey setTarget:self];
699         [hotKey setAction:@selector(decrementRating)];
700         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
701     }
702     ITDebugLog(@"Finished setting up hot keys.");
703 }
704
705 - (void)showCurrentTrackInfo
706 {
707     ITMTRemotePlayerSource  source      = 0;
708     NSString               *title       = nil;
709     NSString               *album       = nil;
710     NSString               *artist      = nil;
711     NSString               *time        = nil;
712     NSString               *track       = nil;
713     NSImage                *art         = nil;
714     int                     rating      = -1;
715     
716     NS_DURING
717         source      = [[self currentRemote] currentSource];
718         title       = [[self currentRemote] currentSongTitle];
719     NS_HANDLER
720         [self networkError:localException];
721     NS_ENDHANDLER
722     
723     ITDebugLog(@"Showing track info status window.");
724     
725     if ( title ) {
726
727         if ( [df boolForKey:@"showAlbum"] ) {
728             NS_DURING
729                 album = [[self currentRemote] currentSongAlbum];
730             NS_HANDLER
731                 [self networkError:localException];
732             NS_ENDHANDLER
733         }
734
735         if ( [df boolForKey:@"showArtist"] ) {
736             NS_DURING
737                 artist = [[self currentRemote] currentSongArtist];
738             NS_HANDLER
739                 [self networkError:localException];
740             NS_ENDHANDLER
741         }
742
743         if ( [df boolForKey:@"showTime"] ) {
744             NS_DURING
745                 time = [NSString stringWithFormat:@"%@: %@ / %@",
746                 @"Time",
747                 [[self currentRemote] currentSongElapsed],
748                 [[self currentRemote] currentSongLength]];
749             NS_HANDLER
750                 [self networkError:localException];
751             NS_ENDHANDLER
752         }
753
754         if ( [df boolForKey:@"showTrackNumber"] ) {
755             int trackNo    = 0;
756             int trackCount = 0;
757             
758             NS_DURING
759                 trackNo    = [[self currentRemote] currentSongTrack];
760                 trackCount = [[self currentRemote] currentAlbumTrackCount];
761             NS_HANDLER
762                 [self networkError:localException];
763             NS_ENDHANDLER
764             
765             if ( (trackNo > 0) || (trackCount > 0) ) {
766                 track = [NSString stringWithFormat:@"%@: %i %@ %i",
767                     @"Track", trackNo, @"of", trackCount];
768             }
769         }
770
771         if ( [df boolForKey:@"showTrackRating"] ) {
772             float currentRating = 0;
773             
774             NS_DURING
775                 currentRating = [[self currentRemote] currentSongRating];
776             NS_HANDLER
777                 [self networkError:localException];
778             NS_ENDHANDLER
779             
780             if (currentRating >= 0.0) {
781                 rating = ( currentRating * 5 );
782             }
783         }
784         
785         if ( [df boolForKey:@"showAlbumArtwork"] ) {
786              NS_DURING
787                 art = [[self currentRemote] currentSongAlbumArt];
788             NS_HANDLER
789                 [self networkError:localException];
790             NS_ENDHANDLER
791         }
792         
793     } else {
794         title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
795     }
796
797     [statusWindowController showSongInfoWindowWithSource:source
798                                                    title:title
799                                                    album:album
800                                                   artist:artist
801                                                     time:time
802                                                    track:track
803                                                   rating:rating
804                                                    image:art];
805 }
806
807 - (void)showUpcomingSongs
808 {
809     int numSongs = 0;
810     NS_DURING
811         numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
812     NS_HANDLER
813         [self networkError:localException];
814     NS_ENDHANDLER
815     
816     ITDebugLog(@"Showing upcoming songs status window.");
817     NS_DURING
818         if (numSongs > 0) {
819             int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
820             NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
821             int curTrack = [[self currentRemote] currentSongIndex];
822             int i;
823     
824             for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
825                 if (i <= numSongs) {
826                     [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
827                 }
828             }
829             
830             if ([songList count] == 0) {
831                 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
832             }
833             
834             [statusWindowController showUpcomingSongsWindowWithTitles:songList];
835         } else {
836             [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
837         }
838     NS_HANDLER
839         [self networkError:localException];
840     NS_ENDHANDLER
841 }
842
843 - (void)incrementVolume
844 {
845     NS_DURING
846         float volume  = [[self currentRemote] volume];
847         float dispVol = volume;
848         ITDebugLog(@"Incrementing volume.");
849         volume  += 0.110;
850         dispVol += 0.100;
851         
852         if (volume > 1.0) {
853             volume  = 1.0;
854             dispVol = 1.0;
855         }
856     
857         ITDebugLog(@"Setting volume to %f", volume);
858         [[self currentRemote] setVolume:volume];
859     
860         // Show volume status window
861         [statusWindowController showVolumeWindowWithLevel:dispVol];
862     NS_HANDLER
863         [self networkError:localException];
864     NS_ENDHANDLER
865 }
866
867 - (void)decrementVolume
868 {
869     NS_DURING
870         float volume  = [[self currentRemote] volume];
871         float dispVol = volume;
872         ITDebugLog(@"Decrementing volume.");
873         volume  -= 0.090;
874         dispVol -= 0.100;
875     
876         if (volume < 0.0) {
877             volume  = 0.0;
878             dispVol = 0.0;
879         }
880         
881         ITDebugLog(@"Setting volume to %f", volume);
882         [[self currentRemote] setVolume:volume];
883         
884         //Show volume status window
885         [statusWindowController showVolumeWindowWithLevel:dispVol];
886     NS_HANDLER
887         [self networkError:localException];
888     NS_ENDHANDLER
889 }
890
891 - (void)incrementRating
892 {
893     NS_DURING
894         float rating = [[self currentRemote] currentSongRating];
895         ITDebugLog(@"Incrementing rating.");
896         
897         if ([[self currentRemote] currentPlaylistIndex] == 0) {
898             ITDebugLog(@"No song playing, rating change aborted.");
899             return;
900         }
901         
902         rating += 0.2;
903         if (rating > 1.0) {
904             rating = 1.0;
905         }
906         ITDebugLog(@"Setting rating to %f", rating);
907         [[self currentRemote] setCurrentSongRating:rating];
908         
909         //Show rating status window
910         [statusWindowController showRatingWindowWithRating:rating];
911     NS_HANDLER
912         [self networkError:localException];
913     NS_ENDHANDLER
914 }
915
916 - (void)decrementRating
917 {
918     NS_DURING
919         float rating = [[self currentRemote] currentSongRating];
920         ITDebugLog(@"Decrementing rating.");
921         
922         if ([[self currentRemote] currentPlaylistIndex] == 0) {
923             ITDebugLog(@"No song playing, rating change aborted.");
924             return;
925         }
926         
927         rating -= 0.2;
928         if (rating < 0.0) {
929             rating = 0.0;
930         }
931         ITDebugLog(@"Setting rating to %f", rating);
932         [[self currentRemote] setCurrentSongRating:rating];
933         
934         //Show rating status window
935         [statusWindowController showRatingWindowWithRating:rating];
936     NS_HANDLER
937         [self networkError:localException];
938     NS_ENDHANDLER
939 }
940
941 - (void)toggleLoop
942 {
943     NS_DURING
944         ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
945         ITDebugLog(@"Toggling repeat mode.");
946         switch (repeatMode) {
947             case ITMTRemotePlayerRepeatOff:
948                 repeatMode = ITMTRemotePlayerRepeatAll;
949             break;
950             case ITMTRemotePlayerRepeatAll:
951                 repeatMode = ITMTRemotePlayerRepeatOne;
952             break;
953             case ITMTRemotePlayerRepeatOne:
954                 repeatMode = ITMTRemotePlayerRepeatOff;
955             break;
956         }
957         ITDebugLog(@"Setting repeat mode to %i", repeatMode);
958         [[self currentRemote] setRepeatMode:repeatMode];
959         
960         //Show loop status window
961         [statusWindowController showRepeatWindowWithMode:repeatMode];
962     NS_HANDLER
963         [self networkError:localException];
964     NS_ENDHANDLER
965 }
966
967 - (void)toggleShuffle
968 {
969     NS_DURING
970         BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
971         ITDebugLog(@"Toggling shuffle mode.");
972         [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
973         //Show shuffle status window
974         ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
975         [statusWindowController showShuffleWindow:newShuffleEnabled];
976     NS_HANDLER
977         [self networkError:localException];
978     NS_ENDHANDLER
979 }
980
981 - (void)registerNowOK
982 {
983     [[StatusWindow sharedWindow] setLocked:NO];
984     [[StatusWindow sharedWindow] vanish:self];
985     [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
986
987     [self blingNow];
988 }
989
990 - (void)registerNowCancel
991 {
992     [[StatusWindow sharedWindow] setLocked:NO];
993     [[StatusWindow sharedWindow] vanish:self];
994     [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
995
996     [NSApp terminate:self];
997 }
998
999 /*************************************************************************/
1000 #pragma mark -
1001 #pragma mark NETWORK HANDLERS
1002 /*************************************************************************/
1003
1004 - (void)setServerStatus:(BOOL)newStatus
1005 {
1006     if (newStatus) {
1007         //Turn on
1008         [networkController setServerStatus:YES];
1009     } else {
1010         //Tear down
1011         [networkController setServerStatus:NO];
1012     }
1013 }
1014
1015 - (int)connectToServer
1016 {
1017     int result;
1018     ITDebugLog(@"Attempting to connect to shared remote.");
1019     result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
1020     //Connect
1021     if (result == 1) {
1022         [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1023         currentRemote = [[[networkController networkObject] remote] retain];
1024         [refreshTimer invalidate];
1025         refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1026                                 target:self
1027                                 selector:@selector(timerUpdate)
1028                                 userInfo:nil
1029                                 repeats:YES] retain];
1030         [self timerUpdate];
1031         ITDebugLog(@"Connection successful.");
1032         return 1;
1033     } else if (result == 0) {
1034         ITDebugLog(@"Connection failed.");
1035         currentRemote = [remoteArray objectAtIndex:0];
1036         return 0;
1037     } else {
1038         //Do something about the password being invalid
1039         ITDebugLog(@"Connection failed.");
1040         currentRemote = [remoteArray objectAtIndex:0];
1041         return -1;
1042     }
1043 }
1044
1045 - (BOOL)disconnectFromServer
1046 {
1047     ITDebugLog(@"Disconnecting from shared remote.");
1048     //Disconnect
1049     [currentRemote release];
1050     currentRemote = [remoteArray objectAtIndex:0];
1051     [networkController disconnect];
1052     [self timerUpdate];
1053     return YES;
1054 }
1055
1056 - (void)checkForRemoteServer:(NSTimer *)timer
1057 {
1058     ITDebugLog(@"Checking for remote server.");
1059     if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1060         ITDebugLog(@"Remote server found.");
1061         [timer invalidate];
1062         if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1063             [[StatusWindowController sharedController] showReconnectQueryWindow];
1064         }
1065     } else {
1066         ITDebugLog(@"Remote server not found.");
1067     }
1068 }
1069
1070 - (void)networkError:(NSException *)exception
1071 {
1072     ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1073     if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1074         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);
1075         if ([self disconnectFromServer]) {
1076             [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1077             [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
1078         } else {
1079             ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1080         }
1081     }
1082 }
1083
1084 - (void)reconnect
1085 {
1086     if ([self connectToServer] == 0) {
1087         [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
1088     }
1089     [[StatusWindow sharedWindow] setLocked:NO];
1090     [[StatusWindow sharedWindow] vanish:self];
1091     [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1092 }
1093
1094 - (void)cancelReconnect
1095 {
1096     [[StatusWindow sharedWindow] setLocked:NO];
1097     [[StatusWindow sharedWindow] vanish:self];
1098     [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1099 }
1100
1101 /*************************************************************************/
1102 #pragma mark -
1103 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1104 /*************************************************************************/
1105
1106 - (void)applicationLaunched:(NSNotification *)note
1107 {
1108     NS_DURING
1109         if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]]) {
1110             ITDebugLog(@"Remote application launched.");
1111             playerRunningState = ITMTRemotePlayerRunning;
1112             [[self currentRemote] begin];
1113             [self setLatestSongIdentifier:@""];
1114             [self timerUpdate];
1115             refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1116                                 target:self
1117                                 selector:@selector(timerUpdate)
1118                                 userInfo:nil
1119                                 repeats:YES] retain];
1120             //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1121             [self setupHotKeys];
1122         }
1123     NS_HANDLER
1124         [self networkError:localException];
1125     NS_ENDHANDLER
1126 }
1127
1128  - (void)applicationTerminated:(NSNotification *)note
1129  {
1130     NS_DURING
1131         if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]]) {
1132             ITDebugLog(@"Remote application terminated.");
1133             playerRunningState = ITMTRemotePlayerNotRunning;
1134             [[self currentRemote] halt];
1135             [refreshTimer invalidate];
1136             [refreshTimer release];
1137             refreshTimer = nil;
1138             [self clearHotKeys];
1139             
1140             if ([df objectForKey:@"ShowPlayer"] != nil) {
1141                 ITHotKey *hotKey;
1142                 ITDebugLog(@"Setting up show player hot key.");
1143                 hotKey = [[ITHotKey alloc] init];
1144                 [hotKey setName:@"ShowPlayer"];
1145                 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1146                 [hotKey setTarget:self];
1147                 [hotKey setAction:@selector(showPlayer)];
1148                 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1149             }
1150         }
1151     NS_HANDLER
1152         [self networkError:localException];
1153     NS_ENDHANDLER
1154  }
1155
1156
1157 /*************************************************************************/
1158 #pragma mark -
1159 #pragma mark NSApplication DELEGATE METHODS
1160 /*************************************************************************/
1161
1162 - (void)applicationWillTerminate:(NSNotification *)note
1163 {
1164     [networkController stopRemoteServerSearch];
1165     [self clearHotKeys];
1166     [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1167 }
1168
1169
1170 /*************************************************************************/
1171 #pragma mark -
1172 #pragma mark DEALLOCATION METHOD
1173 /*************************************************************************/
1174
1175 - (void)dealloc
1176 {
1177     [self applicationTerminated:nil];
1178     [bling release];
1179     [statusItem release];
1180     [statusWindowController release];
1181     [menuController release];
1182     [networkController release];
1183     [super dealloc];
1184 }
1185
1186 @end