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