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