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 <ITKit/ITCategory-NSMenu.h>
10 #import "StatusWindow.h"
11 #import "StatusWindowController.h"
12 #import "StatusItemHack.h"
14 @interface NSCarbonMenuImpl:NSObject
20 + (void)setupForNoMenuBar;
24 - (void)itemChanged:fp8;
25 - (void)itemAdded:fp8;
26 - (void)itemRemoved:fp8;
27 - (void)performActionWithHighlightingForItemAtIndex:(int)fp8;
28 - (void)performMenuAction:(SEL)fp8 withTarget:fp12;
29 - (void)setupCarbonMenuBar;
30 - (void)setAsMainCarbonMenuBar;
31 - (void)clearAsMainCarbonMenuBar;
32 - (void)popUpMenu:fp8 atLocation:(NSPoint)fp12 width:(float)fp20 forView:fp24 withSelectedItem:(int)fp28 withFont:fp32;
33 - (void)_popUpContextMenu:fp8 withEvent:fp12 forView:fp16 withFont:fp20;
34 - (void)_popUpContextMenu:fp8 withEvent:fp12 forView:fp16;
38 @implementation NSImage (SmoothAdditions)
40 - (NSImage *)imageScaledSmoothlyToSize:(NSSize)scaledSize
43 NSImageRep *rep = [self bestRepresentationForDevice:nil];
45 newImage = [[NSImage alloc] initWithSize:scaledSize];
48 [[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
49 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
50 [rep drawInRect:NSMakeRect(3, 3, scaledSize.width - 6, scaledSize.height - 6)];
52 [newImage unlockFocus];
53 return [newImage autorelease];
58 @interface MainController(Private)
59 - (ITMTRemote *)loadRemote;
60 - (void)setLatestSongIdentifier:(NSString *)newIdentifier;
61 - (void)applicationLaunched:(NSNotification *)note;
62 - (void)applicationTerminated:(NSNotification *)note;
65 static MainController *sharedController;
67 @implementation MainController
69 + (MainController *)sharedController
71 return sharedController;
74 /*************************************************************************/
76 #pragma mark INITIALIZATION/DEALLOCATION METHODS
77 /*************************************************************************/
81 if ( ( self = [super init] ) ) {
82 sharedController = self;
84 remoteArray = [[NSMutableArray alloc] initWithCapacity:1];
85 [[PreferencesController sharedPrefs] setController:self];
86 statusWindowController = [StatusWindowController sharedController];
87 menuController = [[MenuController alloc] init];
88 df = [[NSUserDefaults standardUserDefaults] retain];
95 - (void)applicationDidFinishLaunching:(NSNotification *)note
97 //Turn on debug mode if needed
98 if ([df boolForKey:@"ITDebugMode"]) {
102 if (([df integerForKey:@"appVersion"] < 1200) && ([df integerForKey:@"SongsInAdvance"] > 0)) {
103 [df removePersistentDomainForName:@"com.ithinksw.menutunes"];
105 [[PreferencesController sharedPrefs] registerDefaults];
106 [[StatusWindowController sharedController] showPreferencesUpdateWindow];
109 currentRemote = [self loadRemote];
110 [[self currentRemote] begin];
112 //Turn on network stuff if needed
113 networkController = [[NetworkController alloc] init];
114 if ([df boolForKey:@"enableSharing"]) {
115 [self setServerStatus:YES];
116 } else if ([df boolForKey:@"useSharedPlayer"]) {
117 [self checkForRemoteServerAndConnectImmediately:YES];
120 //Setup for notification of the remote player launching or quitting
121 [[[NSWorkspace sharedWorkspace] notificationCenter]
123 selector:@selector(applicationTerminated:)
124 name:NSWorkspaceDidTerminateApplicationNotification
127 [[[NSWorkspace sharedWorkspace] notificationCenter]
129 selector:@selector(applicationLaunched:)
130 name:NSWorkspaceDidLaunchApplicationNotification
133 if (![df objectForKey:@"menu"]) { // If this is nil, defaults have never been registered.
134 [[PreferencesController sharedPrefs] registerDefaults];
137 if ([df boolForKey:@"ITMTNoStatusItem"]) {
140 [StatusItemHack install];
141 statusItem = [[ITStatusItem alloc]
142 initWithStatusBar:[NSStatusBar systemStatusBar]
143 withLength:NSSquareStatusItemLength];
146 bling = [[MTBlingController alloc] init];
148 registerTimer = [[NSTimer scheduledTimerWithTimeInterval:10.0
150 selector:@selector(blingTime)
152 repeats:YES] retain];
155 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
156 [self applicationLaunched:nil];
158 if ([df boolForKey:@"LaunchPlayerWithMT"])
161 [self applicationTerminated:nil];
164 [self networkError:localException];
167 [statusItem setImage:[NSImage imageNamed:@"MenuNormal"]];
168 [statusItem setAlternateImage:[NSImage imageNamed:@"MenuInverted"]];
170 [networkController startRemoteServerSearch];
174 - (ITMTRemote *)loadRemote
176 NSString *folderPath = [[NSBundle mainBundle] builtInPlugInsPath];
177 ITDebugLog(@"Gathering remotes.");
179 NSArray *bundlePathList = [NSBundle pathsForResourcesOfType:@"remote" inDirectory:folderPath];
180 NSEnumerator *enumerator = [bundlePathList objectEnumerator];
181 NSString *bundlePath;
183 while ( (bundlePath = [enumerator nextObject]) ) {
184 NSBundle* remoteBundle = [NSBundle bundleWithPath:bundlePath];
187 Class remoteClass = [remoteBundle principalClass];
189 if ([remoteClass conformsToProtocol:@protocol(ITMTRemote)] &&
190 [(NSObject *)remoteClass isKindOfClass:[NSObject class]]) {
191 id remote = [remoteClass remote];
192 ITDebugLog(@"Adding remote at path %@", bundlePath);
193 [remoteArray addObject:remote];
198 // if ( [remoteArray count] > 0 ) { // UNCOMMENT WHEN WE HAVE > 1 PLUGIN
199 // if ( [remoteArray count] > 1 ) {
200 // [remoteArray sortUsingSelector:@selector(sortAlpha:)];
202 // [self loadModuleAccessUI]; //Comment out this line to disable remote visibility
205 // NSLog(@"%@", [remoteArray objectAtIndex:0]); //DEBUG
206 return [remoteArray objectAtIndex:0];
209 /*************************************************************************/
211 #pragma mark INSTANCE METHODS
212 /*************************************************************************/
214 /*- (void)startTimerInNewThread
216 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
217 NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
218 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:0.5
220 selector:@selector(timerUpdate)
222 repeats:YES] retain];
224 ITDebugLog(@"Timer started.");
228 - (void)setBlingTime:(NSDate*)date
230 NSMutableDictionary *globalPrefs;
232 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
234 [globalPrefs setObject:date forKey:@"ITMTTrialStart"];
235 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
237 [globalPrefs removeObjectForKey:@"ITMTTrialStart"];
238 [globalPrefs removeObjectForKey:@"ITMTTrialVers"];
240 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
242 [globalPrefs release];
245 - (NSDate*)getBlingTime
248 return [[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialStart"];
253 NSDate *now = [NSDate date];
254 if (![self blingBling]) {
255 if ( (! [self getBlingTime] ) || ([now timeIntervalSinceDate:[self getBlingTime]] < 0) ) {
256 [self setBlingTime:now];
257 } else if ([[[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialVers"] intValue] < MT_CURRENT_VERSION) {
258 if ([now timeIntervalSinceDate:[self getBlingTime]] >= 345600) {
259 [self setBlingTime:[now addTimeInterval:-259200]];
261 NSMutableDictionary *globalPrefs;
263 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
264 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
265 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
267 [globalPrefs release];
271 if ( ([now timeIntervalSinceDate:[self getBlingTime]] >= 604800) && (blinged != YES) ) {
273 [statusItem setEnabled:NO];
275 if ([refreshTimer isValid]) {
276 [refreshTimer invalidate];
278 [statusWindowController showRegistrationQueryWindow];
282 [statusItem setEnabled:YES];
284 if (![refreshTimer isValid]) {
285 [refreshTimer release];
286 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
288 selector:@selector(timerUpdate)
290 repeats:YES] retain];
294 [self setBlingTime:nil];
305 if ( ! ([bling checkDone] == 2475) ) {
312 - (BOOL)songIsPlaying
314 NSString *identifier = nil;
316 identifier = [[self currentRemote] playerStateUniqueIdentifier];
318 [self networkError:localException];
320 return ( ! ([identifier isEqualToString:@"0-0"]) );
323 - (BOOL)radioIsPlaying
325 ITMTRemotePlayerPlaylistClass class = nil;
327 class = [[self currentRemote] currentPlaylistClass];
329 [self networkError:localException];
331 return (class == ITMTRemotePlayerRadioPlaylist );
336 NSString *identifier = nil;
338 identifier = [[self currentRemote] playerStateUniqueIdentifier];
340 [self networkError:localException];
342 return ( ! [identifier isEqualToString:_latestSongIdentifier] );
345 - (NSString *)latestSongIdentifier
347 return _latestSongIdentifier;
350 - (void)setLatestSongIdentifier:(NSString *)newIdentifier
352 ITDebugLog(@"Setting latest song identifier:");
353 ITDebugLog(@" - Identifier: %@", newIdentifier);
354 [_latestSongIdentifier autorelease];
355 _latestSongIdentifier = [newIdentifier retain];
360 if ([[self currentRemote] playerStateUniqueIdentifier] == nil) {
361 [statusItem setEnabled:NO];
362 [statusItem setToolTip:@"iTunes not responding."];
364 } else if (![statusItem isEnabled]) {
365 [statusItem setEnabled:YES];
366 [statusItem setToolTip:_toolTip];
370 if ( [self songChanged] && (timerUpdating != YES) && (playerRunningState == ITMTRemotePlayerRunning) ) {
371 ITDebugLog(@"The song changed.");
372 if ([df boolForKey:@"runScripts"]) {
373 NSArray *scripts = [[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"]];
374 NSEnumerator *scriptsEnum = [scripts objectEnumerator];
375 NSString *nextScript;
376 ITDebugLog(@"Running AppleScripts for song change.");
377 while ( (nextScript = [scriptsEnum nextObject]) ) {
379 NSAppleScript *currentScript = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"] stringByAppendingPathComponent:nextScript]] error:&error];
380 ITDebugLog(@"Running script: %@", nextScript);
381 if (!currentScript || ![currentScript executeAndReturnError:nil]) {
382 ITDebugLog(@"Error running script %@.", nextScript);
384 [currentScript release];
389 [statusItem setEnabled:NO];
392 latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
393 [menuController rebuildSubmenus];
395 if ( [df boolForKey:@"showSongInfoOnChange"] ) {
396 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
399 [self setLatestSongIdentifier:[[self currentRemote] playerStateUniqueIdentifier]];
401 //Create the tooltip for the status item
402 if ( [df boolForKey:@"showToolTip"] ) {
403 NSString *artist = [[self currentRemote] currentSongArtist];
404 NSString *title = [[self currentRemote] currentSongTitle];
405 ITDebugLog(@"Creating status item tooltip.");
407 _toolTip = [NSString stringWithFormat:@"%@ - %@", artist, title];
411 _toolTip = @"No Song Playing";
413 [statusItem setToolTip:_toolTip];
415 [statusItem setToolTip:nil];
418 [self networkError:localException];
422 [statusItem setEnabled:YES];
425 if ([networkController isConnectedToServer]) {
426 [statusItem setMenu:([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) ? [menuController menu] : [menuController menuForNoPlayer]];
432 ITDebugLog(@"Menu clicked.");
433 if ([networkController isConnectedToServer]) {
434 //Used the cached version
439 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
440 [statusItem setMenu:[menuController menu]];
442 [statusItem setMenu:[menuController menuForNoPlayer]];
445 [self networkError:localException];
458 ITMTRemotePlayerPlayingState state = [[self currentRemote] playerPlayingState];
459 ITDebugLog(@"Play/Pause toggled");
460 if (state == ITMTRemotePlayerPlaying) {
461 [[self currentRemote] pause];
462 } else if ((state == ITMTRemotePlayerForwarding) || (state == ITMTRemotePlayerRewinding)) {
463 [[self currentRemote] pause];
464 [[self currentRemote] play];
466 [[self currentRemote] play];
469 [self networkError:localException];
477 ITDebugLog(@"Going to next song.");
479 [[self currentRemote] goToNextSong];
481 [self networkError:localException];
488 ITDebugLog(@"Going to previous song.");
490 [[self currentRemote] goToPreviousSong];
492 [self networkError:localException];
499 ITDebugLog(@"Fast forwarding.");
501 [[self currentRemote] forward];
503 [self networkError:localException];
510 ITDebugLog(@"Rewinding.");
512 [[self currentRemote] rewind];
514 [self networkError:localException];
519 - (void)selectPlaylistAtIndex:(int)index
521 ITDebugLog(@"Selecting playlist %i", index);
523 [[self currentRemote] switchToPlaylistAtIndex:(index % 1000) ofSourceAtIndex:(index / 1000)];
524 //[[self currentRemote] switchToPlaylistAtIndex:index];
526 [self networkError:localException];
531 - (void)selectSongAtIndex:(int)index
533 ITDebugLog(@"Selecting song %i", index);
535 [[self currentRemote] switchToSongAtIndex:index];
537 [self networkError:localException];
542 - (void)selectSongRating:(int)rating
544 ITDebugLog(@"Selecting song rating %i", rating);
546 [[self currentRemote] setCurrentSongRating:(float)rating / 100.0];
548 [self networkError:localException];
553 - (void)selectEQPresetAtIndex:(int)index
555 ITDebugLog(@"Selecting EQ preset %i", index);
558 [[self currentRemote] setEqualizerEnabled:![[self currentRemote] equalizerEnabled]];
560 [[self currentRemote] switchToEQAtIndex:index];
563 [self networkError:localException];
568 - (void)makePlaylistWithTerm:(NSString *)term ofType:(int)type
570 ITDebugLog(@"Making playlist with term %@, type %i", term, type);
572 [[self currentRemote] makePlaylistWithTerm:term ofType:type];
574 [self networkError:localException];
576 ITDebugLog(@"Done making playlist");
581 ITDebugLog(@"Beginning show player.");
582 //if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
583 ITDebugLog(@"Showing player interface.");
585 [[self currentRemote] showPrimaryInterface];
587 [self networkError:localException];
590 ITDebugLog(@"Launching player.");
593 if ( (path = [df stringForKey:@"CustomPlayerPath"]) ) {
595 pathITDebugLog(@"Showing player interface."); = [[self currentRemote] playerFullName];
597 if (![[NSWorkspace sharedWorkspace] launchApplication:path]) {
598 ITDebugLog(@"Error Launching Player");
601 [self networkError:localException];
604 ITDebugLog(@"Finished show player.");
607 - (void)showPreferences
609 ITDebugLog(@"Show preferences.");
610 [[PreferencesController sharedPrefs] showPrefsWindow:self];
613 - (void)showPreferencesAndClose
615 ITDebugLog(@"Show preferences.");
616 [[PreferencesController sharedPrefs] showPrefsWindow:self];
617 [[StatusWindow sharedWindow] setLocked:NO];
618 [[StatusWindow sharedWindow] vanish:self];
619 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
622 - (void)showTestWindow
624 [self showCurrentTrackInfo];
627 - (void)quitMenuTunes
629 ITDebugLog(@"Quitting MenuTunes.");
630 [NSApp terminate:self];
636 - (MenuController *)menuController
638 return menuController;
641 - (void)closePreferences
643 ITDebugLog(@"Preferences closed.");
644 if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
649 - (ITMTRemote *)currentRemote
651 if ([networkController isConnectedToServer] && ![[networkController networkObject] isValid]) {
652 [self networkError:nil];
655 return currentRemote;
666 NSEnumerator *hotKeyEnumerator = [[[ITHotKeyCenter sharedCenter] allHotKeys] objectEnumerator];
667 ITHotKey *nextHotKey;
668 ITDebugLog(@"Clearing hot keys.");
669 while ( (nextHotKey = [hotKeyEnumerator nextObject]) ) {
670 [[ITHotKeyCenter sharedCenter] unregisterHotKey:nextHotKey];
672 ITDebugLog(@"Done clearing hot keys.");
678 ITDebugLog(@"Setting up hot keys.");
680 if (playerRunningState == ITMTRemotePlayerNotRunning && ![[NetworkController sharedController] isConnectedToServer]) {
684 if ([df objectForKey:@"PlayPause"] != nil) {
685 ITDebugLog(@"Setting up play pause hot key.");
686 hotKey = [[ITHotKey alloc] init];
687 [hotKey setName:@"PlayPause"];
688 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PlayPause"]]];
689 [hotKey setTarget:self];
690 [hotKey setAction:@selector(playPause)];
691 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
694 if ([df objectForKey:@"NextTrack"] != nil) {
695 ITDebugLog(@"Setting up next track hot key.");
696 hotKey = [[ITHotKey alloc] init];
697 [hotKey setName:@"NextTrack"];
698 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"NextTrack"]]];
699 [hotKey setTarget:self];
700 [hotKey setAction:@selector(nextSong)];
701 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
704 if ([df objectForKey:@"PrevTrack"] != nil) {
705 ITDebugLog(@"Setting up previous track hot key.");
706 hotKey = [[ITHotKey alloc] init];
707 [hotKey setName:@"PrevTrack"];
708 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PrevTrack"]]];
709 [hotKey setTarget:self];
710 [hotKey setAction:@selector(prevSong)];
711 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
714 if ([df objectForKey:@"FastForward"] != nil) {
715 ITDebugLog(@"Setting up fast forward hot key.");
716 hotKey = [[ITHotKey alloc] init];
717 [hotKey setName:@"FastForward"];
718 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"FastForward"]]];
719 [hotKey setTarget:self];
720 [hotKey setAction:@selector(fastForward)];
721 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
724 if ([df objectForKey:@"Rewind"] != nil) {
725 ITDebugLog(@"Setting up rewind hot key.");
726 hotKey = [[ITHotKey alloc] init];
727 [hotKey setName:@"Rewind"];
728 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"Rewind"]]];
729 [hotKey setTarget:self];
730 [hotKey setAction:@selector(rewind)];
731 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
734 if ([df objectForKey:@"ShowPlayer"] != nil) {
735 ITDebugLog(@"Setting up show player hot key.");
736 hotKey = [[ITHotKey alloc] init];
737 [hotKey setName:@"ShowPlayer"];
738 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
739 [hotKey setTarget:self];
740 [hotKey setAction:@selector(showPlayer)];
741 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
744 if ([df objectForKey:@"TrackInfo"] != nil) {
745 ITDebugLog(@"Setting up track info hot key.");
746 hotKey = [[ITHotKey alloc] init];
747 [hotKey setName:@"TrackInfo"];
748 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"TrackInfo"]]];
749 [hotKey setTarget:self];
750 [hotKey setAction:@selector(showCurrentTrackInfo)];
751 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
754 if ([df objectForKey:@"UpcomingSongs"] != nil) {
755 ITDebugLog(@"Setting up upcoming songs hot key.");
756 hotKey = [[ITHotKey alloc] init];
757 [hotKey setName:@"UpcomingSongs"];
758 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"UpcomingSongs"]]];
759 [hotKey setTarget:self];
760 [hotKey setAction:@selector(showUpcomingSongs)];
761 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
764 if ([df objectForKey:@"ToggleLoop"] != nil) {
765 ITDebugLog(@"Setting up toggle loop hot key.");
766 hotKey = [[ITHotKey alloc] init];
767 [hotKey setName:@"ToggleLoop"];
768 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleLoop"]]];
769 [hotKey setTarget:self];
770 [hotKey setAction:@selector(toggleLoop)];
771 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
774 if ([df objectForKey:@"ToggleShuffle"] != nil) {
775 ITDebugLog(@"Setting up toggle shuffle hot key.");
776 hotKey = [[ITHotKey alloc] init];
777 [hotKey setName:@"ToggleShuffle"];
778 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShuffle"]]];
779 [hotKey setTarget:self];
780 [hotKey setAction:@selector(toggleShuffle)];
781 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
784 if ([df objectForKey:@"IncrementVolume"] != nil) {
785 ITDebugLog(@"Setting up increment volume hot key.");
786 hotKey = [[ITHotKey alloc] init];
787 [hotKey setName:@"IncrementVolume"];
788 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementVolume"]]];
789 [hotKey setTarget:self];
790 [hotKey setAction:@selector(incrementVolume)];
791 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
794 if ([df objectForKey:@"DecrementVolume"] != nil) {
795 ITDebugLog(@"Setting up decrement volume hot key.");
796 hotKey = [[ITHotKey alloc] init];
797 [hotKey setName:@"DecrementVolume"];
798 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementVolume"]]];
799 [hotKey setTarget:self];
800 [hotKey setAction:@selector(decrementVolume)];
801 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
804 if ([df objectForKey:@"IncrementRating"] != nil) {
805 ITDebugLog(@"Setting up increment rating hot key.");
806 hotKey = [[ITHotKey alloc] init];
807 [hotKey setName:@"IncrementRating"];
808 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementRating"]]];
809 [hotKey setTarget:self];
810 [hotKey setAction:@selector(incrementRating)];
811 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
814 if ([df objectForKey:@"DecrementRating"] != nil) {
815 ITDebugLog(@"Setting up decrement rating hot key.");
816 hotKey = [[ITHotKey alloc] init];
817 [hotKey setName:@"DecrementRating"];
818 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementRating"]]];
819 [hotKey setTarget:self];
820 [hotKey setAction:@selector(decrementRating)];
821 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
824 if ([df objectForKey:@"PopupMenu"] != nil) {
825 ITDebugLog(@"Setting up popup menu hot key.");
826 hotKey = [[ITHotKey alloc] init];
827 [hotKey setName:@"PopupMenu"];
828 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PopupMenu"]]];
829 [hotKey setTarget:self];
830 [hotKey setAction:@selector(popupMenu)];
831 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
835 for (i = 0; i <= 5; i++) {
836 NSString *curName = [NSString stringWithFormat:@"SetRating%i", i];
837 if ([df objectForKey:curName] != nil) {
838 ITDebugLog(@"Setting up set rating %i hot key.", i);
839 hotKey = [[ITHotKey alloc] init];
840 [hotKey setName:curName];
841 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:curName]]];
842 [hotKey setTarget:self];
843 [hotKey setAction:@selector(setRating:)];
844 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
847 ITDebugLog(@"Finished setting up hot keys.");
850 - (void)showCurrentTrackInfo
852 ITMTRemotePlayerSource source = 0;
853 NSString *title = nil;
854 NSString *album = nil;
855 NSString *artist = nil;
856 NSString *composer = nil;
857 NSString *time = nil;
858 NSString *track = nil;
863 ITDebugLog(@"Showing track info status window.");
866 source = [[self currentRemote] currentSource];
867 title = [[self currentRemote] currentSongTitle];
869 [self networkError:localException];
873 if ( [df boolForKey:@"showAlbumArtwork"] ) {
874 NSSize oldSize, newSize;
876 art = [[self currentRemote] currentSongAlbumArt];
877 oldSize = [art size];
878 if (oldSize.width > oldSize.height) newSize = NSMakeSize(110,oldSize.height * (110.0f / oldSize.width));
879 else newSize = NSMakeSize(oldSize.width * (110.0f / oldSize.height),110);
880 art = [[[[NSImage alloc] initWithData:[art TIFFRepresentation]] autorelease] imageScaledSmoothlyToSize:newSize];
882 [self networkError:localException];
886 if ( [df boolForKey:@"showAlbum"] ) {
888 album = [[self currentRemote] currentSongAlbum];
890 [self networkError:localException];
894 if ( [df boolForKey:@"showArtist"] ) {
896 artist = [[self currentRemote] currentSongArtist];
898 [self networkError:localException];
902 if ( [df boolForKey:@"showComposer"] ) {
904 composer = [[self currentRemote] currentSongComposer];
906 [self networkError:localException];
910 if ( [df boolForKey:@"showTime"] ) {
912 time = [NSString stringWithFormat:@"%@: %@ / %@",
913 NSLocalizedString(@"time", @"Time"),
914 [[self currentRemote] currentSongElapsed],
915 [[self currentRemote] currentSongLength]];
917 [self networkError:localException];
921 if ( [df boolForKey:@"showTrackNumber"] ) {
926 trackNo = [[self currentRemote] currentSongTrack];
927 trackCount = [[self currentRemote] currentAlbumTrackCount];
929 [self networkError:localException];
932 if ( (trackNo > 0) || (trackCount > 0) ) {
933 track = [NSString stringWithFormat:@"%@: %i %@ %i",
934 @"Track", trackNo, @"of", trackCount];
938 if ( [df boolForKey:@"showTrackRating"] ) {
939 float currentRating = 0;
942 currentRating = [[self currentRemote] currentSongRating];
944 [self networkError:localException];
947 if (currentRating >= 0.0) {
948 rating = ( currentRating * 5 );
952 if ( [df boolForKey:@"showPlayCount"] && ![self radioIsPlaying] && [[self currentRemote] currentSource] == ITMTRemoteLibrarySource ) {
954 playCount = [[self currentRemote] currentSongPlayCount];
956 [self networkError:localException];
960 title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
962 ITDebugLog(@"Showing current track info status window.");
963 [statusWindowController showSongInfoWindowWithSource:source
975 - (void)showUpcomingSongs
979 numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
981 [self networkError:localException];
984 ITDebugLog(@"Showing upcoming songs status window.");
987 int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
988 NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
989 int curTrack = [[self currentRemote] currentSongIndex];
992 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
994 [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
998 if ([songList count] == 0) {
999 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
1002 [statusWindowController showUpcomingSongsWindowWithTitles:songList];
1004 [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
1007 [self networkError:localException];
1016 NSMenu *menu = [statusItem menu];
1017 [(NSCarbonMenuImpl *)[menu _menuImpl] popUpMenu:menu atLocation:[NSEvent mouseLocation] width:1 forView:nil withSelectedItem:-30 withFont:[NSFont menuFontOfSize:32]];
1022 - (void)incrementVolume
1025 float volume = [[self currentRemote] volume];
1026 float dispVol = volume;
1027 ITDebugLog(@"Incrementing volume.");
1036 ITDebugLog(@"Setting volume to %f", volume);
1037 [[self currentRemote] setVolume:volume];
1039 // Show volume status window
1040 [statusWindowController showVolumeWindowWithLevel:dispVol];
1042 [self networkError:localException];
1046 - (void)decrementVolume
1049 float volume = [[self currentRemote] volume];
1050 float dispVol = volume;
1051 ITDebugLog(@"Decrementing volume.");
1060 ITDebugLog(@"Setting volume to %f", volume);
1061 [[self currentRemote] setVolume:volume];
1063 //Show volume status window
1064 [statusWindowController showVolumeWindowWithLevel:dispVol];
1066 [self networkError:localException];
1070 - (void)incrementRating
1073 float rating = [[self currentRemote] currentSongRating];
1074 ITDebugLog(@"Incrementing rating.");
1076 if ([[self currentRemote] currentPlaylistIndex] == 0) {
1077 ITDebugLog(@"No song playing, rating change aborted.");
1085 ITDebugLog(@"Setting rating to %f", rating);
1086 [[self currentRemote] setCurrentSongRating:rating];
1088 //Show rating status window
1089 [statusWindowController showRatingWindowWithRating:rating];
1091 [self networkError:localException];
1095 - (void)decrementRating
1098 float rating = [[self currentRemote] currentSongRating];
1099 ITDebugLog(@"Decrementing rating.");
1101 if ([[self currentRemote] currentPlaylistIndex] == 0) {
1102 ITDebugLog(@"No song playing, rating change aborted.");
1110 ITDebugLog(@"Setting rating to %f", rating);
1111 [[self currentRemote] setCurrentSongRating:rating];
1113 //Show rating status window
1114 [statusWindowController showRatingWindowWithRating:rating];
1116 [self networkError:localException];
1120 - (void)setRating:(ITHotKey *)sender
1122 int stars = [[sender name] characterAtIndex:9] - 48;
1123 [self selectSongRating:stars * 20];
1124 [statusWindowController showRatingWindowWithRating:(float)stars / 5.0];
1130 ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
1131 ITDebugLog(@"Toggling repeat mode.");
1132 switch (repeatMode) {
1133 case ITMTRemotePlayerRepeatOff:
1134 repeatMode = ITMTRemotePlayerRepeatAll;
1136 case ITMTRemotePlayerRepeatAll:
1137 repeatMode = ITMTRemotePlayerRepeatOne;
1139 case ITMTRemotePlayerRepeatOne:
1140 repeatMode = ITMTRemotePlayerRepeatOff;
1143 ITDebugLog(@"Setting repeat mode to %i", repeatMode);
1144 [[self currentRemote] setRepeatMode:repeatMode];
1146 //Show loop status window
1147 [statusWindowController showRepeatWindowWithMode:repeatMode];
1149 [self networkError:localException];
1153 - (void)toggleShuffle
1156 BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
1157 ITDebugLog(@"Toggling shuffle mode.");
1158 [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
1159 //Show shuffle status window
1160 ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
1161 [statusWindowController showShuffleWindow:newShuffleEnabled];
1163 [self networkError:localException];
1167 - (void)registerNowOK
1169 [[StatusWindow sharedWindow] setLocked:NO];
1170 [[StatusWindow sharedWindow] vanish:self];
1171 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1176 - (void)registerNowCancel
1178 [[StatusWindow sharedWindow] setLocked:NO];
1179 [[StatusWindow sharedWindow] vanish:self];
1180 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1182 [NSApp terminate:self];
1185 /*************************************************************************/
1187 #pragma mark NETWORK HANDLERS
1188 /*************************************************************************/
1190 - (void)setServerStatus:(BOOL)newStatus
1194 [networkController setServerStatus:YES];
1197 [networkController setServerStatus:NO];
1201 - (int)connectToServer
1204 ITDebugLog(@"Attempting to connect to shared remote.");
1205 result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
1208 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1209 currentRemote = [[[networkController networkObject] remote] retain];
1211 [self setupHotKeys];
1212 //playerRunningState = ITMTRemotePlayerRunning;
1213 playerRunningState = [[self currentRemote] playerRunningState];
1215 [refreshTimer invalidate];
1216 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1218 selector:@selector(timerUpdate)
1220 repeats:YES] retain];
1222 ITDebugLog(@"Connection successful.");
1224 } else if (result == 0) {
1225 ITDebugLog(@"Connection failed.");
1226 currentRemote = [remoteArray objectAtIndex:0];
1229 //Do something about the password being invalid
1230 ITDebugLog(@"Connection failed.");
1231 currentRemote = [remoteArray objectAtIndex:0];
1236 - (BOOL)disconnectFromServer
1238 ITDebugLog(@"Disconnecting from shared remote.");
1240 [currentRemote release];
1241 currentRemote = [remoteArray objectAtIndex:0];
1242 [networkController disconnect];
1244 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
1245 [self applicationLaunched:nil];
1247 [self applicationTerminated:nil];
1253 - (void)checkForRemoteServer
1255 [self checkForRemoteServerAndConnectImmediately:NO];
1258 - (void)checkForRemoteServerAndConnectImmediately:(BOOL)connectImmediately
1260 ITDebugLog(@"Checking for remote server.");
1261 if (!_checkingForServer) {
1262 if (!_serverCheckLock) {
1263 _serverCheckLock = [[NSLock alloc] init];
1265 [_serverCheckLock lock];
1266 _checkingForServer = YES;
1267 [_serverCheckLock unlock];
1268 [NSThread detachNewThreadSelector:@selector(runRemoteServerCheck:) toTarget:self withObject:[NSNumber numberWithBool:connectImmediately]];
1272 - (void)runRemoteServerCheck:(id)sender
1274 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1275 ITDebugLog(@"Remote server check running.");
1276 if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1277 ITDebugLog(@"Remote server found.");
1278 if ([sender boolValue]) {
1279 [self performSelectorOnMainThread:@selector(connectToServer) withObject:nil waitUntilDone:NO];
1281 [self performSelectorOnMainThread:@selector(remoteServerFound:) withObject:nil waitUntilDone:NO];
1284 ITDebugLog(@"Remote server not found.");
1285 [self performSelectorOnMainThread:@selector(remoteServerNotFound:) withObject:nil waitUntilDone:NO];
1287 [_serverCheckLock lock];
1288 _checkingForServer = NO;
1289 [_serverCheckLock unlock];
1293 - (void)remoteServerFound:(id)sender
1295 if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1296 [[StatusWindowController sharedController] showReconnectQueryWindow];
1300 - (void)remoteServerNotFound:(id)sender
1302 if (![[NetworkController sharedController] isConnectedToServer]) {
1303 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1307 - (void)networkError:(NSException *)exception
1309 ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1310 if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1311 //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);
1312 [[StatusWindowController sharedController] showNetworkErrorQueryWindow];
1313 if ([self disconnectFromServer]) {
1314 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1315 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1317 ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1324 /*if ([self connectToServer] == 0) {
1325 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1327 [self checkForRemoteServerAndConnectImmediately:YES];
1328 [[StatusWindow sharedWindow] setLocked:NO];
1329 [[StatusWindow sharedWindow] vanish:self];
1330 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1333 - (void)cancelReconnect
1335 [[StatusWindow sharedWindow] setLocked:NO];
1336 [[StatusWindow sharedWindow] vanish:self];
1337 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1340 /*************************************************************************/
1342 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1343 /*************************************************************************/
1345 - (void)applicationLaunched:(NSNotification *)note
1348 if (!note || ([[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer])) {
1349 ITDebugLog(@"Remote application launched.");
1350 playerRunningState = ITMTRemotePlayerRunning;
1351 [[self currentRemote] begin];
1352 [self setLatestSongIdentifier:@""];
1354 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1356 selector:@selector(timerUpdate)
1358 repeats:YES] retain];
1359 //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1360 [self setupHotKeys];
1363 [self networkError:localException];
1367 - (void)applicationTerminated:(NSNotification *)note
1370 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer]) {
1371 ITDebugLog(@"Remote application terminated.");
1372 playerRunningState = ITMTRemotePlayerNotRunning;
1373 [[self currentRemote] halt];
1374 [refreshTimer invalidate];
1375 [refreshTimer release];
1377 [self clearHotKeys];
1379 if ([df objectForKey:@"ShowPlayer"] != nil) {
1381 ITDebugLog(@"Setting up show player hot key.");
1382 hotKey = [[ITHotKey alloc] init];
1383 [hotKey setName:@"ShowPlayer"];
1384 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1385 [hotKey setTarget:self];
1386 [hotKey setAction:@selector(showPlayer)];
1387 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1391 [self networkError:localException];
1396 /*************************************************************************/
1398 #pragma mark NSApplication DELEGATE METHODS
1399 /*************************************************************************/
1401 - (void)applicationWillTerminate:(NSNotification *)note
1403 [networkController stopRemoteServerSearch];
1404 [self clearHotKeys];
1405 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1409 /*************************************************************************/
1411 #pragma mark DEALLOCATION METHOD
1412 /*************************************************************************/
1416 [self applicationTerminated:nil];
1418 [statusItem release];
1419 [statusWindowController release];
1420 [menuController release];
1421 [networkController release];
1422 [_serverCheckLock release];