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