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