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