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"
13 @interface NSCarbonMenuImpl:NSObject
19 + (void)setupForNoMenuBar;
23 - (void)itemChanged:fp8;
24 - (void)itemAdded:fp8;
25 - (void)itemRemoved:fp8;
26 - (void)performActionWithHighlightingForItemAtIndex:(int)fp8;
27 - (void)performMenuAction:(SEL)fp8 withTarget:fp12;
28 - (void)setupCarbonMenuBar;
29 - (void)setAsMainCarbonMenuBar;
30 - (void)clearAsMainCarbonMenuBar;
31 - (void)popUpMenu:fp8 atLocation:(NSPoint)fp12 width:(float)fp20 forView:fp24 withSelectedItem:(int)fp28 withFont:fp32;
32 - (void)_popUpContextMenu:fp8 withEvent:fp12 forView:fp16 withFont:fp20;
33 - (void)_popUpContextMenu:fp8 withEvent:fp12 forView:fp16;
37 @implementation NSImage (SmoothAdditions)
39 - (NSImage *)imageScaledSmoothlyToSize:(NSSize)scaledSize
42 NSImageRep *rep = [self bestRepresentationForDevice:nil];
44 newImage = [[NSImage alloc] initWithSize:scaledSize];
47 [[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
48 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
49 [rep drawInRect:NSMakeRect(3, 3, scaledSize.width - 6, scaledSize.height - 6)];
51 [newImage unlockFocus];
52 return [newImage autorelease];
57 @interface MainController(Private)
58 - (ITMTRemote *)loadRemote;
59 - (void)setLatestSongIdentifier:(NSString *)newIdentifier;
60 - (void)applicationLaunched:(NSNotification *)note;
61 - (void)applicationTerminated:(NSNotification *)note;
64 static MainController *sharedController;
66 @implementation MainController
68 + (MainController *)sharedController
70 return sharedController;
73 /*************************************************************************/
75 #pragma mark INITIALIZATION/DEALLOCATION METHODS
76 /*************************************************************************/
80 if ( ( self = [super init] ) ) {
81 sharedController = self;
83 remoteArray = [[NSMutableArray alloc] initWithCapacity:1];
84 [[PreferencesController sharedPrefs] setController:self];
85 statusWindowController = [StatusWindowController sharedController];
86 menuController = [[MenuController alloc] init];
87 df = [[NSUserDefaults standardUserDefaults] retain];
94 - (void)applicationDidFinishLaunching:(NSNotification *)note
96 //Turn on debug mode if needed
97 if ([df boolForKey:@"ITDebugMode"]) {
101 if (([df integerForKey:@"appVersion"] < 1200) && ([df integerForKey:@"SongsInAdvance"] > 0)) {
102 [df removePersistentDomainForName:@"com.ithinksw.menutunes"];
104 [[PreferencesController sharedPrefs] registerDefaults];
105 [[StatusWindowController sharedController] showPreferencesUpdateWindow];
108 currentRemote = [self loadRemote];
109 [[self currentRemote] begin];
111 //Turn on network stuff if needed
112 networkController = [[NetworkController alloc] init];
113 if ([df boolForKey:@"enableSharing"]) {
114 [self setServerStatus:YES];
115 } else if ([df boolForKey:@"useSharedPlayer"]) {
116 [self checkForRemoteServerAndConnectImmediately:YES];
119 //Setup for notification of the remote player launching or quitting
120 [[[NSWorkspace sharedWorkspace] notificationCenter]
122 selector:@selector(applicationTerminated:)
123 name:NSWorkspaceDidTerminateApplicationNotification
126 [[[NSWorkspace sharedWorkspace] notificationCenter]
128 selector:@selector(applicationLaunched:)
129 name:NSWorkspaceDidLaunchApplicationNotification
132 if (![df objectForKey:@"menu"]) { // If this is nil, defaults have never been registered.
133 [[PreferencesController sharedPrefs] registerDefaults];
136 if ([df boolForKey:@"ITMTNoStatusItem"]) {
139 [StatusItemHack install];
140 statusItem = [[ITStatusItem alloc]
141 initWithStatusBar:[NSStatusBar systemStatusBar]
142 withLength:NSSquareStatusItemLength];
145 bling = [[MTBlingController alloc] init];
147 registerTimer = [[NSTimer scheduledTimerWithTimeInterval:10.0
149 selector:@selector(blingTime)
151 repeats:YES] retain];
154 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
155 [self applicationLaunched:nil];
157 if ([df boolForKey:@"LaunchPlayerWithMT"])
160 [self applicationTerminated:nil];
163 [self networkError:localException];
166 [statusItem setImage:[NSImage imageNamed:@"MenuNormal"]];
167 [statusItem setAlternateImage:[NSImage imageNamed:@"MenuInverted"]];
169 [networkController startRemoteServerSearch];
173 - (ITMTRemote *)loadRemote
175 NSString *folderPath = [[NSBundle mainBundle] builtInPlugInsPath];
176 ITDebugLog(@"Gathering remotes.");
178 NSArray *bundlePathList = [NSBundle pathsForResourcesOfType:@"remote" inDirectory:folderPath];
179 NSEnumerator *enumerator = [bundlePathList objectEnumerator];
180 NSString *bundlePath;
182 while ( (bundlePath = [enumerator nextObject]) ) {
183 NSBundle* remoteBundle = [NSBundle bundleWithPath:bundlePath];
186 Class remoteClass = [remoteBundle principalClass];
188 if ([remoteClass conformsToProtocol:@protocol(ITMTRemote)] &&
189 [(NSObject *)remoteClass isKindOfClass:[NSObject class]]) {
190 id remote = [remoteClass remote];
191 ITDebugLog(@"Adding remote at path %@", bundlePath);
192 [remoteArray addObject:remote];
197 // if ( [remoteArray count] > 0 ) { // UNCOMMENT WHEN WE HAVE > 1 PLUGIN
198 // if ( [remoteArray count] > 1 ) {
199 // [remoteArray sortUsingSelector:@selector(sortAlpha:)];
201 // [self loadModuleAccessUI]; //Comment out this line to disable remote visibility
204 // NSLog(@"%@", [remoteArray objectAtIndex:0]); //DEBUG
205 return [remoteArray objectAtIndex:0];
208 /*************************************************************************/
210 #pragma mark INSTANCE METHODS
211 /*************************************************************************/
213 /*- (void)startTimerInNewThread
215 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
216 NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
217 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:0.5
219 selector:@selector(timerUpdate)
221 repeats:YES] retain];
223 ITDebugLog(@"Timer started.");
227 - (void)setBlingTime:(NSDate*)date
229 NSMutableDictionary *globalPrefs;
231 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
233 [globalPrefs setObject:date forKey:@"ITMTTrialStart"];
234 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
236 [globalPrefs removeObjectForKey:@"ITMTTrialStart"];
237 [globalPrefs removeObjectForKey:@"ITMTTrialVers"];
239 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
241 [globalPrefs release];
244 - (NSDate*)getBlingTime
247 return [[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialStart"];
252 NSDate *now = [NSDate date];
253 if (![self blingBling]) {
254 if ( (! [self getBlingTime] ) || ([now timeIntervalSinceDate:[self getBlingTime]] < 0) ) {
255 [self setBlingTime:now];
256 } else if ([[[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialVers"] intValue] < MT_CURRENT_VERSION) {
257 if ([now timeIntervalSinceDate:[self getBlingTime]] >= 345600) {
258 [self setBlingTime:[now addTimeInterval:-259200]];
260 NSMutableDictionary *globalPrefs;
262 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
263 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
264 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
266 [globalPrefs release];
270 if ( ([now timeIntervalSinceDate:[self getBlingTime]] >= 604800) && (blinged != YES) ) {
272 [statusItem setEnabled:NO];
274 if ([refreshTimer isValid]) {
275 [refreshTimer invalidate];
277 [statusWindowController showRegistrationQueryWindow];
281 [statusItem setEnabled:YES];
283 if (![refreshTimer isValid]) {
284 [refreshTimer release];
285 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
287 selector:@selector(timerUpdate)
289 repeats:YES] retain];
293 [self setBlingTime:nil];
304 if ( ! ([bling checkDone] == 2475) ) {
311 - (BOOL)songIsPlaying
313 NSString *identifier = nil;
315 identifier = [[self currentRemote] playerStateUniqueIdentifier];
317 [self networkError:localException];
319 return ( ! ([identifier isEqualToString:@"0-0"]) );
322 - (BOOL)radioIsPlaying
324 ITMTRemotePlayerPlaylistClass class = nil;
326 class = [[self currentRemote] currentPlaylistClass];
328 [self networkError:localException];
330 return (class == ITMTRemotePlayerRadioPlaylist );
335 NSString *identifier = nil;
337 identifier = [[self currentRemote] playerStateUniqueIdentifier];
339 [self networkError:localException];
341 return ( ! [identifier isEqualToString:_latestSongIdentifier] );
344 - (NSString *)latestSongIdentifier
346 return _latestSongIdentifier;
349 - (void)setLatestSongIdentifier:(NSString *)newIdentifier
351 ITDebugLog(@"Setting latest song identifier:");
352 ITDebugLog(@" - Identifier: %@", newIdentifier);
353 [_latestSongIdentifier autorelease];
354 _latestSongIdentifier = [newIdentifier retain];
359 if ( [self songChanged] && (timerUpdating != YES) && (playerRunningState == ITMTRemotePlayerRunning) ) {
360 ITDebugLog(@"The song changed.");
362 if ([df boolForKey:@"runScripts"]) {
363 NSArray *scripts = [[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"]];
364 NSEnumerator *scriptsEnum = [scripts objectEnumerator];
365 NSString *nextScript;
366 ITDebugLog(@"Running AppleScripts for song change.");
367 while ( (nextScript = [scriptsEnum nextObject]) ) {
369 NSAppleScript *currentScript = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"] stringByAppendingPathComponent:nextScript]] error:&error];
370 ITDebugLog(@"Running script: %@", nextScript);
371 if (!currentScript || ![currentScript executeAndReturnError:nil]) {
372 ITDebugLog(@"Error running script %@.", nextScript);
374 [currentScript release];
379 [statusItem setEnabled:NO];
382 latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
383 [menuController rebuildSubmenus];
385 if ( [df boolForKey:@"showSongInfoOnChange"] ) {
386 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
389 [self setLatestSongIdentifier:[[self currentRemote] playerStateUniqueIdentifier]];
391 //Create the tooltip for the status item
392 if ( [df boolForKey:@"showToolTip"] ) {
393 NSString *artist = [[self currentRemote] currentSongArtist];
394 NSString *title = [[self currentRemote] currentSongTitle];
396 ITDebugLog(@"Creating status item tooltip.");
398 toolTip = [NSString stringWithFormat:@"%@ - %@", artist, title];
402 toolTip = @"No Song Playing";
404 [statusItem setToolTip:toolTip];
406 [statusItem setToolTip:nil];
409 [self networkError:localException];
413 [statusItem setEnabled:YES];
416 if ([networkController isConnectedToServer]) {
417 [statusItem setMenu:([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) ? [menuController menu] : [menuController menuForNoPlayer]];
423 ITDebugLog(@"Menu clicked.");
424 if ([networkController isConnectedToServer]) {
425 //Used the cached version
430 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
431 [statusItem setMenu:[menuController menu]];
433 [statusItem setMenu:[menuController menuForNoPlayer]];
436 [self networkError:localException];
449 ITMTRemotePlayerPlayingState state = [[self currentRemote] playerPlayingState];
450 ITDebugLog(@"Play/Pause toggled");
451 if (state == ITMTRemotePlayerPlaying) {
452 [[self currentRemote] pause];
453 } else if ((state == ITMTRemotePlayerForwarding) || (state == ITMTRemotePlayerRewinding)) {
454 [[self currentRemote] pause];
455 [[self currentRemote] play];
457 [[self currentRemote] play];
460 [self networkError:localException];
468 ITDebugLog(@"Going to next song.");
470 [[self currentRemote] goToNextSong];
472 [self networkError:localException];
479 ITDebugLog(@"Going to previous song.");
481 [[self currentRemote] goToPreviousSong];
483 [self networkError:localException];
490 ITDebugLog(@"Fast forwarding.");
492 [[self currentRemote] forward];
494 [self networkError:localException];
501 ITDebugLog(@"Rewinding.");
503 [[self currentRemote] rewind];
505 [self networkError:localException];
510 - (void)selectPlaylistAtIndex:(int)index
512 ITDebugLog(@"Selecting playlist %i", index);
514 [[self currentRemote] switchToPlaylistAtIndex:(index % 1000) ofSourceAtIndex:(index / 1000)];
515 //[[self currentRemote] switchToPlaylistAtIndex:index];
517 [self networkError:localException];
522 - (void)selectSongAtIndex:(int)index
524 ITDebugLog(@"Selecting song %i", index);
526 [[self currentRemote] switchToSongAtIndex:index];
528 [self networkError:localException];
533 - (void)selectSongRating:(int)rating
535 ITDebugLog(@"Selecting song rating %i", rating);
537 [[self currentRemote] setCurrentSongRating:(float)rating / 100.0];
539 [self networkError:localException];
544 - (void)selectEQPresetAtIndex:(int)index
546 ITDebugLog(@"Selecting EQ preset %i", index);
549 [[self currentRemote] setEqualizerEnabled:![[self currentRemote] equalizerEnabled]];
551 [[self currentRemote] switchToEQAtIndex:index];
554 [self networkError:localException];
561 ITDebugLog(@"Beginning show player.");
562 //if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
563 ITDebugLog(@"Showing player interface.");
565 [[self currentRemote] showPrimaryInterface];
567 [self networkError:localException];
570 ITDebugLog(@"Launching player.");
573 if ( (path = [df stringForKey:@"CustomPlayerPath"]) ) {
575 pathITDebugLog(@"Showing player interface."); = [[self currentRemote] playerFullName];
577 if (![[NSWorkspace sharedWorkspace] launchApplication:path]) {
578 ITDebugLog(@"Error Launching Player");
581 [self networkError:localException];
584 ITDebugLog(@"Finished show player.");
587 - (void)showPreferences
589 ITDebugLog(@"Show preferences.");
590 [[PreferencesController sharedPrefs] showPrefsWindow:self];
593 - (void)showPreferencesAndClose
595 ITDebugLog(@"Show preferences.");
596 [[PreferencesController sharedPrefs] showPrefsWindow:self];
597 [[StatusWindow sharedWindow] setLocked:NO];
598 [[StatusWindow sharedWindow] vanish:self];
599 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
602 - (void)showTestWindow
604 [self showCurrentTrackInfo];
607 - (void)quitMenuTunes
609 ITDebugLog(@"Quitting MenuTunes.");
610 [NSApp terminate:self];
616 - (MenuController *)menuController
618 return menuController;
621 - (void)closePreferences
623 ITDebugLog(@"Preferences closed.");
624 if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
629 - (ITMTRemote *)currentRemote
631 if ([networkController isConnectedToServer] && ![[networkController networkObject] isValid]) {
632 [self networkError:nil];
635 return currentRemote;
646 NSEnumerator *hotKeyEnumerator = [[[ITHotKeyCenter sharedCenter] allHotKeys] objectEnumerator];
647 ITHotKey *nextHotKey;
648 ITDebugLog(@"Clearing hot keys.");
649 while ( (nextHotKey = [hotKeyEnumerator nextObject]) ) {
650 [[ITHotKeyCenter sharedCenter] unregisterHotKey:nextHotKey];
652 ITDebugLog(@"Done clearing hot keys.");
658 ITDebugLog(@"Setting up hot keys.");
660 if (playerRunningState == ITMTRemotePlayerNotRunning && ![[NetworkController sharedController] isConnectedToServer]) {
664 if ([df objectForKey:@"PlayPause"] != nil) {
665 ITDebugLog(@"Setting up play pause hot key.");
666 hotKey = [[ITHotKey alloc] init];
667 [hotKey setName:@"PlayPause"];
668 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PlayPause"]]];
669 [hotKey setTarget:self];
670 [hotKey setAction:@selector(playPause)];
671 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
674 if ([df objectForKey:@"NextTrack"] != nil) {
675 ITDebugLog(@"Setting up next track hot key.");
676 hotKey = [[ITHotKey alloc] init];
677 [hotKey setName:@"NextTrack"];
678 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"NextTrack"]]];
679 [hotKey setTarget:self];
680 [hotKey setAction:@selector(nextSong)];
681 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
684 if ([df objectForKey:@"PrevTrack"] != nil) {
685 ITDebugLog(@"Setting up previous track hot key.");
686 hotKey = [[ITHotKey alloc] init];
687 [hotKey setName:@"PrevTrack"];
688 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PrevTrack"]]];
689 [hotKey setTarget:self];
690 [hotKey setAction:@selector(prevSong)];
691 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
694 if ([df objectForKey:@"FastForward"] != nil) {
695 ITDebugLog(@"Setting up fast forward hot key.");
696 hotKey = [[ITHotKey alloc] init];
697 [hotKey setName:@"FastForward"];
698 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"FastForward"]]];
699 [hotKey setTarget:self];
700 [hotKey setAction:@selector(fastForward)];
701 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
704 if ([df objectForKey:@"Rewind"] != nil) {
705 ITDebugLog(@"Setting up rewind hot key.");
706 hotKey = [[ITHotKey alloc] init];
707 [hotKey setName:@"Rewind"];
708 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"Rewind"]]];
709 [hotKey setTarget:self];
710 [hotKey setAction:@selector(rewind)];
711 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
714 if ([df objectForKey:@"ShowPlayer"] != nil) {
715 ITDebugLog(@"Setting up show player hot key.");
716 hotKey = [[ITHotKey alloc] init];
717 [hotKey setName:@"ShowPlayer"];
718 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
719 [hotKey setTarget:self];
720 [hotKey setAction:@selector(showPlayer)];
721 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
724 if ([df objectForKey:@"TrackInfo"] != nil) {
725 ITDebugLog(@"Setting up track info hot key.");
726 hotKey = [[ITHotKey alloc] init];
727 [hotKey setName:@"TrackInfo"];
728 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"TrackInfo"]]];
729 [hotKey setTarget:self];
730 [hotKey setAction:@selector(showCurrentTrackInfo)];
731 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
734 if ([df objectForKey:@"UpcomingSongs"] != nil) {
735 ITDebugLog(@"Setting up upcoming songs hot key.");
736 hotKey = [[ITHotKey alloc] init];
737 [hotKey setName:@"UpcomingSongs"];
738 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"UpcomingSongs"]]];
739 [hotKey setTarget:self];
740 [hotKey setAction:@selector(showUpcomingSongs)];
741 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
744 if ([df objectForKey:@"ToggleLoop"] != nil) {
745 ITDebugLog(@"Setting up toggle loop hot key.");
746 hotKey = [[ITHotKey alloc] init];
747 [hotKey setName:@"ToggleLoop"];
748 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleLoop"]]];
749 [hotKey setTarget:self];
750 [hotKey setAction:@selector(toggleLoop)];
751 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
754 if ([df objectForKey:@"ToggleShuffle"] != nil) {
755 ITDebugLog(@"Setting up toggle shuffle hot key.");
756 hotKey = [[ITHotKey alloc] init];
757 [hotKey setName:@"ToggleShuffle"];
758 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShuffle"]]];
759 [hotKey setTarget:self];
760 [hotKey setAction:@selector(toggleShuffle)];
761 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
764 if ([df objectForKey:@"IncrementVolume"] != nil) {
765 ITDebugLog(@"Setting up increment volume hot key.");
766 hotKey = [[ITHotKey alloc] init];
767 [hotKey setName:@"IncrementVolume"];
768 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementVolume"]]];
769 [hotKey setTarget:self];
770 [hotKey setAction:@selector(incrementVolume)];
771 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
774 if ([df objectForKey:@"DecrementVolume"] != nil) {
775 ITDebugLog(@"Setting up decrement volume hot key.");
776 hotKey = [[ITHotKey alloc] init];
777 [hotKey setName:@"DecrementVolume"];
778 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementVolume"]]];
779 [hotKey setTarget:self];
780 [hotKey setAction:@selector(decrementVolume)];
781 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
784 if ([df objectForKey:@"IncrementRating"] != nil) {
785 ITDebugLog(@"Setting up increment rating hot key.");
786 hotKey = [[ITHotKey alloc] init];
787 [hotKey setName:@"IncrementRating"];
788 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementRating"]]];
789 [hotKey setTarget:self];
790 [hotKey setAction:@selector(incrementRating)];
791 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
794 if ([df objectForKey:@"DecrementRating"] != nil) {
795 ITDebugLog(@"Setting up decrement rating hot key.");
796 hotKey = [[ITHotKey alloc] init];
797 [hotKey setName:@"DecrementRating"];
798 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementRating"]]];
799 [hotKey setTarget:self];
800 [hotKey setAction:@selector(decrementRating)];
801 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
804 if ([df objectForKey:@"PopupMenu"] != nil) {
805 ITDebugLog(@"Setting up popup menu hot key.");
806 hotKey = [[ITHotKey alloc] init];
807 [hotKey setName:@"PopupMenu"];
808 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PopupMenu"]]];
809 [hotKey setTarget:self];
810 [hotKey setAction:@selector(popupMenu)];
811 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
813 ITDebugLog(@"Finished setting up hot keys.");
816 - (void)showCurrentTrackInfo
818 ITMTRemotePlayerSource source = 0;
819 NSString *title = nil;
820 NSString *album = nil;
821 NSString *artist = nil;
822 NSString *composer = nil;
823 NSString *time = nil;
824 NSString *track = nil;
829 ITDebugLog(@"Showing track info status window.");
832 source = [[self currentRemote] currentSource];
833 title = [[self currentRemote] currentSongTitle];
835 [self networkError:localException];
839 if ( [df boolForKey:@"showAlbumArtwork"] ) {
840 NSSize oldSize, newSize;
842 art = [[self currentRemote] currentSongAlbumArt];
843 oldSize = [art size];
844 if (oldSize.width > oldSize.height) newSize = NSMakeSize(110,oldSize.height * (110.0f / oldSize.width));
845 else newSize = NSMakeSize(oldSize.width * (110.0f / oldSize.height),110);
846 art = [[[[NSImage alloc] initWithData:[art TIFFRepresentation]] autorelease] imageScaledSmoothlyToSize:newSize];
848 [self networkError:localException];
852 if ( [df boolForKey:@"showAlbum"] ) {
854 album = [[self currentRemote] currentSongAlbum];
856 [self networkError:localException];
860 if ( [df boolForKey:@"showArtist"] ) {
862 artist = [[self currentRemote] currentSongArtist];
864 [self networkError:localException];
868 if ( [df boolForKey:@"showComposer"] ) {
870 composer = [[self currentRemote] currentSongComposer];
872 [self networkError:localException];
876 if ( [df boolForKey:@"showTime"] ) {
878 time = [NSString stringWithFormat:@"%@: %@ / %@",
880 [[self currentRemote] currentSongElapsed],
881 [[self currentRemote] currentSongLength]];
883 [self networkError:localException];
887 if ( [df boolForKey:@"showTrackNumber"] ) {
892 trackNo = [[self currentRemote] currentSongTrack];
893 trackCount = [[self currentRemote] currentAlbumTrackCount];
895 [self networkError:localException];
898 if ( (trackNo > 0) || (trackCount > 0) ) {
899 track = [NSString stringWithFormat:@"%@: %i %@ %i",
900 @"Track", trackNo, @"of", trackCount];
904 if ( [df boolForKey:@"showTrackRating"] ) {
905 float currentRating = 0;
908 currentRating = [[self currentRemote] currentSongRating];
910 [self networkError:localException];
913 if (currentRating >= 0.0) {
914 rating = ( currentRating * 5 );
918 if ( [df boolForKey:@"showPlayCount"] ) {
920 playCount = [[self currentRemote] currentSongPlayCount];
922 [self networkError:localException];
926 title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
928 ITDebugLog(@"Showing current track info status window.");
929 [statusWindowController showSongInfoWindowWithSource:source
941 - (void)showUpcomingSongs
945 numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
947 [self networkError:localException];
950 ITDebugLog(@"Showing upcoming songs status window.");
953 int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
954 NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
955 int curTrack = [[self currentRemote] currentSongIndex];
958 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
960 [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
964 if ([songList count] == 0) {
965 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
968 [statusWindowController showUpcomingSongsWindowWithTitles:songList];
970 [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
973 [self networkError:localException];
979 NSMenu *menu = [menuController menu];
980 [(NSCarbonMenuImpl *)[menu _menuImpl] popUpMenu:menu atLocation:[NSEvent mouseLocation] width:1 forView:nil withSelectedItem:-30 withFont:[NSFont menuFontOfSize:32]];
983 - (void)incrementVolume
986 float volume = [[self currentRemote] volume];
987 float dispVol = volume;
988 ITDebugLog(@"Incrementing volume.");
997 ITDebugLog(@"Setting volume to %f", volume);
998 [[self currentRemote] setVolume:volume];
1000 // Show volume status window
1001 [statusWindowController showVolumeWindowWithLevel:dispVol];
1003 [self networkError:localException];
1007 - (void)decrementVolume
1010 float volume = [[self currentRemote] volume];
1011 float dispVol = volume;
1012 ITDebugLog(@"Decrementing volume.");
1021 ITDebugLog(@"Setting volume to %f", volume);
1022 [[self currentRemote] setVolume:volume];
1024 //Show volume status window
1025 [statusWindowController showVolumeWindowWithLevel:dispVol];
1027 [self networkError:localException];
1031 - (void)incrementRating
1034 float rating = [[self currentRemote] currentSongRating];
1035 ITDebugLog(@"Incrementing rating.");
1037 if ([[self currentRemote] currentPlaylistIndex] == 0) {
1038 ITDebugLog(@"No song playing, rating change aborted.");
1046 ITDebugLog(@"Setting rating to %f", rating);
1047 [[self currentRemote] setCurrentSongRating:rating];
1049 //Show rating status window
1050 [statusWindowController showRatingWindowWithRating:rating];
1052 [self networkError:localException];
1056 - (void)decrementRating
1059 float rating = [[self currentRemote] currentSongRating];
1060 ITDebugLog(@"Decrementing rating.");
1062 if ([[self currentRemote] currentPlaylistIndex] == 0) {
1063 ITDebugLog(@"No song playing, rating change aborted.");
1071 ITDebugLog(@"Setting rating to %f", rating);
1072 [[self currentRemote] setCurrentSongRating:rating];
1074 //Show rating status window
1075 [statusWindowController showRatingWindowWithRating:rating];
1077 [self networkError:localException];
1084 ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
1085 ITDebugLog(@"Toggling repeat mode.");
1086 switch (repeatMode) {
1087 case ITMTRemotePlayerRepeatOff:
1088 repeatMode = ITMTRemotePlayerRepeatAll;
1090 case ITMTRemotePlayerRepeatAll:
1091 repeatMode = ITMTRemotePlayerRepeatOne;
1093 case ITMTRemotePlayerRepeatOne:
1094 repeatMode = ITMTRemotePlayerRepeatOff;
1097 ITDebugLog(@"Setting repeat mode to %i", repeatMode);
1098 [[self currentRemote] setRepeatMode:repeatMode];
1100 //Show loop status window
1101 [statusWindowController showRepeatWindowWithMode:repeatMode];
1103 [self networkError:localException];
1107 - (void)toggleShuffle
1110 BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
1111 ITDebugLog(@"Toggling shuffle mode.");
1112 [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
1113 //Show shuffle status window
1114 ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
1115 [statusWindowController showShuffleWindow:newShuffleEnabled];
1117 [self networkError:localException];
1121 - (void)registerNowOK
1123 [[StatusWindow sharedWindow] setLocked:NO];
1124 [[StatusWindow sharedWindow] vanish:self];
1125 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1130 - (void)registerNowCancel
1132 [[StatusWindow sharedWindow] setLocked:NO];
1133 [[StatusWindow sharedWindow] vanish:self];
1134 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1136 [NSApp terminate:self];
1139 /*************************************************************************/
1141 #pragma mark NETWORK HANDLERS
1142 /*************************************************************************/
1144 - (void)setServerStatus:(BOOL)newStatus
1148 [networkController setServerStatus:YES];
1151 [networkController setServerStatus:NO];
1155 - (int)connectToServer
1158 ITDebugLog(@"Attempting to connect to shared remote.");
1159 result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
1162 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1163 currentRemote = [[[networkController networkObject] remote] retain];
1165 [self setupHotKeys];
1166 //playerRunningState = ITMTRemotePlayerRunning;
1167 playerRunningState = [[self currentRemote] playerRunningState];
1169 [refreshTimer invalidate];
1170 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1172 selector:@selector(timerUpdate)
1174 repeats:YES] retain];
1176 ITDebugLog(@"Connection successful.");
1178 } else if (result == 0) {
1179 ITDebugLog(@"Connection failed.");
1180 currentRemote = [remoteArray objectAtIndex:0];
1183 //Do something about the password being invalid
1184 ITDebugLog(@"Connection failed.");
1185 currentRemote = [remoteArray objectAtIndex:0];
1190 - (BOOL)disconnectFromServer
1192 ITDebugLog(@"Disconnecting from shared remote.");
1194 [currentRemote release];
1195 currentRemote = [remoteArray objectAtIndex:0];
1196 [networkController disconnect];
1198 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
1199 [self applicationLaunched:nil];
1201 [self applicationTerminated:nil];
1207 - (void)checkForRemoteServer
1209 [self checkForRemoteServerAndConnectImmediately:NO];
1212 - (void)checkForRemoteServerAndConnectImmediately:(BOOL)connectImmediately
1214 ITDebugLog(@"Checking for remote server.");
1215 if (!_checkingForServer) {
1216 if (!_serverCheckLock) {
1217 _serverCheckLock = [[NSLock alloc] init];
1219 [_serverCheckLock lock];
1220 _checkingForServer = YES;
1221 [_serverCheckLock unlock];
1222 [NSThread detachNewThreadSelector:@selector(runRemoteServerCheck:) toTarget:self withObject:[NSNumber numberWithBool:connectImmediately]];
1226 - (void)runRemoteServerCheck:(id)sender
1228 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1229 ITDebugLog(@"Remote server check running.");
1230 if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1231 ITDebugLog(@"Remote server found.");
1232 if ([sender boolValue]) {
1233 [self performSelectorOnMainThread:@selector(connectToServer) withObject:nil waitUntilDone:NO];
1235 [self performSelectorOnMainThread:@selector(remoteServerFound:) withObject:nil waitUntilDone:NO];
1238 ITDebugLog(@"Remote server not found.");
1239 [self performSelectorOnMainThread:@selector(remoteServerNotFound:) withObject:nil waitUntilDone:NO];
1241 [_serverCheckLock lock];
1242 _checkingForServer = NO;
1243 [_serverCheckLock unlock];
1247 - (void)remoteServerFound:(id)sender
1249 if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1250 [[StatusWindowController sharedController] showReconnectQueryWindow];
1254 - (void)remoteServerNotFound:(id)sender
1256 if (![[NetworkController sharedController] isConnectedToServer]) {
1257 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1261 - (void)networkError:(NSException *)exception
1263 ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1264 if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1265 //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);
1266 [[StatusWindowController sharedController] showNetworkErrorQueryWindow];
1267 if ([self disconnectFromServer]) {
1268 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1269 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1271 ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1278 /*if ([self connectToServer] == 0) {
1279 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1281 [self checkForRemoteServerAndConnectImmediately:YES];
1282 [[StatusWindow sharedWindow] setLocked:NO];
1283 [[StatusWindow sharedWindow] vanish:self];
1284 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1287 - (void)cancelReconnect
1289 [[StatusWindow sharedWindow] setLocked:NO];
1290 [[StatusWindow sharedWindow] vanish:self];
1291 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1294 /*************************************************************************/
1296 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1297 /*************************************************************************/
1299 - (void)applicationLaunched:(NSNotification *)note
1302 if (!note || ([[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer])) {
1303 ITDebugLog(@"Remote application launched.");
1304 playerRunningState = ITMTRemotePlayerRunning;
1305 [[self currentRemote] begin];
1306 [self setLatestSongIdentifier:@""];
1308 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1310 selector:@selector(timerUpdate)
1312 repeats:YES] retain];
1313 //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1314 [self setupHotKeys];
1317 [self networkError:localException];
1321 - (void)applicationTerminated:(NSNotification *)note
1324 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer]) {
1325 ITDebugLog(@"Remote application terminated.");
1326 playerRunningState = ITMTRemotePlayerNotRunning;
1327 [[self currentRemote] halt];
1328 [refreshTimer invalidate];
1329 [refreshTimer release];
1331 [self clearHotKeys];
1333 if ([df objectForKey:@"ShowPlayer"] != nil) {
1335 ITDebugLog(@"Setting up show player hot key.");
1336 hotKey = [[ITHotKey alloc] init];
1337 [hotKey setName:@"ShowPlayer"];
1338 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1339 [hotKey setTarget:self];
1340 [hotKey setAction:@selector(showPlayer)];
1341 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1345 [self networkError:localException];
1350 /*************************************************************************/
1352 #pragma mark NSApplication DELEGATE METHODS
1353 /*************************************************************************/
1355 - (void)applicationWillTerminate:(NSNotification *)note
1357 [networkController stopRemoteServerSearch];
1358 [self clearHotKeys];
1359 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1363 /*************************************************************************/
1365 #pragma mark DEALLOCATION METHOD
1366 /*************************************************************************/
1370 [self applicationTerminated:nil];
1372 [statusItem release];
1373 [statusWindowController release];
1374 [menuController release];
1375 [networkController release];
1376 [_serverCheckLock release];