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