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