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 if ([statusItem isEnabled]) {
362 [statusItem setToolTip:@"iTunes not responding."];
365 [statusItem setEnabled:NO];
367 } else if (![statusItem isEnabled]) {
368 [statusItem setEnabled:YES];
369 [statusItem setToolTip:_toolTip];
374 if ( [self songChanged] && (timerUpdating != YES) && (playerRunningState == ITMTRemotePlayerRunning) ) {
375 ITDebugLog(@"The song changed.");
376 if ([df boolForKey:@"runScripts"]) {
377 NSArray *scripts = [[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"]];
378 NSEnumerator *scriptsEnum = [scripts objectEnumerator];
379 NSString *nextScript;
380 ITDebugLog(@"Running AppleScripts for song change.");
381 while ( (nextScript = [scriptsEnum nextObject]) ) {
383 NSAppleScript *currentScript = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"] stringByAppendingPathComponent:nextScript]] error:&error];
384 ITDebugLog(@"Running script: %@", nextScript);
385 if (!currentScript || ![currentScript executeAndReturnError:nil]) {
386 ITDebugLog(@"Error running script %@.", nextScript);
388 [currentScript release];
393 [statusItem setEnabled:NO];
396 latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
397 [menuController rebuildSubmenus];
399 if ( [df boolForKey:@"showSongInfoOnChange"] ) {
400 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
403 [self setLatestSongIdentifier:[[self currentRemote] playerStateUniqueIdentifier]];
405 //Create the tooltip for the status item
406 if ( [df boolForKey:@"showToolTip"] ) {
407 NSString *artist = [[self currentRemote] currentSongArtist];
408 NSString *title = [[self currentRemote] currentSongTitle];
409 ITDebugLog(@"Creating status item tooltip.");
411 _toolTip = [NSString stringWithFormat:@"%@ - %@", artist, title];
415 _toolTip = @"No Song Playing";
417 [statusItem setToolTip:_toolTip];
419 [statusItem setToolTip:nil];
422 [self networkError:localException];
426 [statusItem setEnabled:YES];
429 if ([networkController isConnectedToServer]) {
430 [statusItem setMenu:([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) ? [menuController menu] : [menuController menuForNoPlayer]];
436 ITDebugLog(@"Menu clicked.");
437 if ([networkController isConnectedToServer]) {
438 //Used the cached version
443 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
444 [statusItem setMenu:[menuController menu]];
446 [statusItem setMenu:[menuController menuForNoPlayer]];
449 [self networkError:localException];
462 ITMTRemotePlayerPlayingState state = [[self currentRemote] playerPlayingState];
463 ITDebugLog(@"Play/Pause toggled");
464 if (state == ITMTRemotePlayerPlaying) {
465 [[self currentRemote] pause];
466 } else if ((state == ITMTRemotePlayerForwarding) || (state == ITMTRemotePlayerRewinding)) {
467 [[self currentRemote] pause];
468 [[self currentRemote] play];
470 [[self currentRemote] play];
473 [self networkError:localException];
481 ITDebugLog(@"Going to next song.");
483 [[self currentRemote] goToNextSong];
485 [self networkError:localException];
492 ITDebugLog(@"Going to previous song.");
494 [[self currentRemote] goToPreviousSong];
496 [self networkError:localException];
503 ITDebugLog(@"Fast forwarding.");
505 [[self currentRemote] forward];
507 [self networkError:localException];
514 ITDebugLog(@"Rewinding.");
516 [[self currentRemote] rewind];
518 [self networkError:localException];
523 - (void)selectPlaylistAtIndex:(int)index
525 ITDebugLog(@"Selecting playlist %i", index);
527 [[self currentRemote] switchToPlaylistAtIndex:(index % 1000) ofSourceAtIndex:(index / 1000)];
528 //[[self currentRemote] switchToPlaylistAtIndex:index];
530 [self networkError:localException];
535 - (void)selectSongAtIndex:(int)index
537 ITDebugLog(@"Selecting song %i", index);
539 [[self currentRemote] switchToSongAtIndex:index];
541 [self networkError:localException];
546 - (void)selectSongRating:(int)rating
548 ITDebugLog(@"Selecting song rating %i", rating);
550 [[self currentRemote] setCurrentSongRating:(float)rating / 100.0];
552 [self networkError:localException];
557 - (void)selectEQPresetAtIndex:(int)index
559 ITDebugLog(@"Selecting EQ preset %i", index);
562 [[self currentRemote] setEqualizerEnabled:![[self currentRemote] equalizerEnabled]];
564 [[self currentRemote] switchToEQAtIndex:index];
567 [self networkError:localException];
572 - (void)makePlaylistWithTerm:(NSString *)term ofType:(int)type
574 ITDebugLog(@"Making playlist with term %@, type %i", term, type);
576 [[self currentRemote] makePlaylistWithTerm:term ofType:type];
578 [self networkError:localException];
580 ITDebugLog(@"Done making playlist");
585 ITDebugLog(@"Beginning show player.");
586 //if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
587 ITDebugLog(@"Showing player interface.");
589 [[self currentRemote] showPrimaryInterface];
591 [self networkError:localException];
594 ITDebugLog(@"Launching player.");
597 if ( (path = [df stringForKey:@"CustomPlayerPath"]) ) {
599 pathITDebugLog(@"Showing player interface."); = [[self currentRemote] playerFullName];
601 if (![[NSWorkspace sharedWorkspace] launchApplication:path]) {
602 ITDebugLog(@"Error Launching Player");
605 [self networkError:localException];
608 ITDebugLog(@"Finished show player.");
611 - (void)showPreferences
613 ITDebugLog(@"Show preferences.");
614 [[PreferencesController sharedPrefs] showPrefsWindow:self];
617 - (void)showPreferencesAndClose
619 ITDebugLog(@"Show preferences.");
620 [[PreferencesController sharedPrefs] showPrefsWindow:self];
621 [[StatusWindow sharedWindow] setLocked:NO];
622 [[StatusWindow sharedWindow] vanish:self];
623 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
626 - (void)showTestWindow
628 [self showCurrentTrackInfo];
631 - (void)quitMenuTunes
633 ITDebugLog(@"Quitting MenuTunes.");
634 [NSApp terminate:self];
640 - (MenuController *)menuController
642 return menuController;
645 - (void)closePreferences
647 ITDebugLog(@"Preferences closed.");
648 if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
653 - (ITMTRemote *)currentRemote
655 if ([networkController isConnectedToServer] && ![[networkController networkObject] isValid]) {
656 [self networkError:nil];
659 return currentRemote;
670 NSEnumerator *hotKeyEnumerator = [[[ITHotKeyCenter sharedCenter] allHotKeys] objectEnumerator];
671 ITHotKey *nextHotKey;
672 ITDebugLog(@"Clearing hot keys.");
673 while ( (nextHotKey = [hotKeyEnumerator nextObject]) ) {
674 [[ITHotKeyCenter sharedCenter] unregisterHotKey:nextHotKey];
676 ITDebugLog(@"Done clearing hot keys.");
682 ITDebugLog(@"Setting up hot keys.");
684 if (playerRunningState == ITMTRemotePlayerNotRunning && ![[NetworkController sharedController] isConnectedToServer]) {
688 if ([df objectForKey:@"PlayPause"] != nil) {
689 ITDebugLog(@"Setting up play pause hot key.");
690 hotKey = [[ITHotKey alloc] init];
691 [hotKey setName:@"PlayPause"];
692 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PlayPause"]]];
693 [hotKey setTarget:self];
694 [hotKey setAction:@selector(playPause)];
695 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
698 if ([df objectForKey:@"NextTrack"] != nil) {
699 ITDebugLog(@"Setting up next track hot key.");
700 hotKey = [[ITHotKey alloc] init];
701 [hotKey setName:@"NextTrack"];
702 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"NextTrack"]]];
703 [hotKey setTarget:self];
704 [hotKey setAction:@selector(nextSong)];
705 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
708 if ([df objectForKey:@"PrevTrack"] != nil) {
709 ITDebugLog(@"Setting up previous track hot key.");
710 hotKey = [[ITHotKey alloc] init];
711 [hotKey setName:@"PrevTrack"];
712 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PrevTrack"]]];
713 [hotKey setTarget:self];
714 [hotKey setAction:@selector(prevSong)];
715 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
718 if ([df objectForKey:@"FastForward"] != nil) {
719 ITDebugLog(@"Setting up fast forward hot key.");
720 hotKey = [[ITHotKey alloc] init];
721 [hotKey setName:@"FastForward"];
722 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"FastForward"]]];
723 [hotKey setTarget:self];
724 [hotKey setAction:@selector(fastForward)];
725 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
728 if ([df objectForKey:@"Rewind"] != nil) {
729 ITDebugLog(@"Setting up rewind hot key.");
730 hotKey = [[ITHotKey alloc] init];
731 [hotKey setName:@"Rewind"];
732 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"Rewind"]]];
733 [hotKey setTarget:self];
734 [hotKey setAction:@selector(rewind)];
735 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
738 if ([df objectForKey:@"ShowPlayer"] != nil) {
739 ITDebugLog(@"Setting up show player hot key.");
740 hotKey = [[ITHotKey alloc] init];
741 [hotKey setName:@"ShowPlayer"];
742 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
743 [hotKey setTarget:self];
744 [hotKey setAction:@selector(showPlayer)];
745 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
748 if ([df objectForKey:@"TrackInfo"] != nil) {
749 ITDebugLog(@"Setting up track info hot key.");
750 hotKey = [[ITHotKey alloc] init];
751 [hotKey setName:@"TrackInfo"];
752 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"TrackInfo"]]];
753 [hotKey setTarget:self];
754 [hotKey setAction:@selector(showCurrentTrackInfo)];
755 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
758 if ([df objectForKey:@"UpcomingSongs"] != nil) {
759 ITDebugLog(@"Setting up upcoming songs hot key.");
760 hotKey = [[ITHotKey alloc] init];
761 [hotKey setName:@"UpcomingSongs"];
762 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"UpcomingSongs"]]];
763 [hotKey setTarget:self];
764 [hotKey setAction:@selector(showUpcomingSongs)];
765 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
768 if ([df objectForKey:@"ToggleLoop"] != nil) {
769 ITDebugLog(@"Setting up toggle loop hot key.");
770 hotKey = [[ITHotKey alloc] init];
771 [hotKey setName:@"ToggleLoop"];
772 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleLoop"]]];
773 [hotKey setTarget:self];
774 [hotKey setAction:@selector(toggleLoop)];
775 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
778 if ([df objectForKey:@"ToggleShuffle"] != nil) {
779 ITDebugLog(@"Setting up toggle shuffle hot key.");
780 hotKey = [[ITHotKey alloc] init];
781 [hotKey setName:@"ToggleShuffle"];
782 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShuffle"]]];
783 [hotKey setTarget:self];
784 [hotKey setAction:@selector(toggleShuffle)];
785 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
788 if ([df objectForKey:@"IncrementVolume"] != nil) {
789 ITDebugLog(@"Setting up increment volume hot key.");
790 hotKey = [[ITHotKey alloc] init];
791 [hotKey setName:@"IncrementVolume"];
792 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementVolume"]]];
793 [hotKey setTarget:self];
794 [hotKey setAction:@selector(incrementVolume)];
795 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
798 if ([df objectForKey:@"DecrementVolume"] != nil) {
799 ITDebugLog(@"Setting up decrement volume hot key.");
800 hotKey = [[ITHotKey alloc] init];
801 [hotKey setName:@"DecrementVolume"];
802 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementVolume"]]];
803 [hotKey setTarget:self];
804 [hotKey setAction:@selector(decrementVolume)];
805 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
808 if ([df objectForKey:@"IncrementRating"] != nil) {
809 ITDebugLog(@"Setting up increment rating hot key.");
810 hotKey = [[ITHotKey alloc] init];
811 [hotKey setName:@"IncrementRating"];
812 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementRating"]]];
813 [hotKey setTarget:self];
814 [hotKey setAction:@selector(incrementRating)];
815 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
818 if ([df objectForKey:@"DecrementRating"] != nil) {
819 ITDebugLog(@"Setting up decrement rating hot key.");
820 hotKey = [[ITHotKey alloc] init];
821 [hotKey setName:@"DecrementRating"];
822 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementRating"]]];
823 [hotKey setTarget:self];
824 [hotKey setAction:@selector(decrementRating)];
825 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
828 if ([df objectForKey:@"PopupMenu"] != nil) {
829 ITDebugLog(@"Setting up popup menu hot key.");
830 hotKey = [[ITHotKey alloc] init];
831 [hotKey setName:@"PopupMenu"];
832 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PopupMenu"]]];
833 [hotKey setTarget:self];
834 [hotKey setAction:@selector(popupMenu)];
835 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
839 for (i = 0; i <= 5; i++) {
840 NSString *curName = [NSString stringWithFormat:@"SetRating%i", i];
841 if ([df objectForKey:curName] != nil) {
842 ITDebugLog(@"Setting up set rating %i hot key.", i);
843 hotKey = [[ITHotKey alloc] init];
844 [hotKey setName:curName];
845 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:curName]]];
846 [hotKey setTarget:self];
847 [hotKey setAction:@selector(setRating:)];
848 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
851 ITDebugLog(@"Finished setting up hot keys.");
854 - (void)showCurrentTrackInfo
856 ITMTRemotePlayerSource source = 0;
857 NSString *title = nil;
858 NSString *album = nil;
859 NSString *artist = nil;
860 NSString *composer = nil;
861 NSString *time = nil;
862 NSString *track = nil;
867 ITDebugLog(@"Showing track info status window.");
870 source = [[self currentRemote] currentSource];
871 title = [[self currentRemote] currentSongTitle];
873 [self networkError:localException];
877 if ( [df boolForKey:@"showAlbumArtwork"] ) {
878 NSSize oldSize, newSize;
880 art = [[self currentRemote] currentSongAlbumArt];
881 oldSize = [art size];
882 if (oldSize.width > oldSize.height) newSize = NSMakeSize(110,oldSize.height * (110.0f / oldSize.width));
883 else newSize = NSMakeSize(oldSize.width * (110.0f / oldSize.height),110);
884 art = [[[[NSImage alloc] initWithData:[art TIFFRepresentation]] autorelease] imageScaledSmoothlyToSize:newSize];
886 [self networkError:localException];
890 if ( [df boolForKey:@"showAlbum"] ) {
892 album = [[self currentRemote] currentSongAlbum];
894 [self networkError:localException];
898 if ( [df boolForKey:@"showArtist"] ) {
900 artist = [[self currentRemote] currentSongArtist];
902 [self networkError:localException];
906 if ( [df boolForKey:@"showComposer"] ) {
908 composer = [[self currentRemote] currentSongComposer];
910 [self networkError:localException];
914 if ( [df boolForKey:@"showTime"] ) {
916 time = [NSString stringWithFormat:@"%@: %@ / %@",
917 NSLocalizedString(@"time", @"Time"),
918 [[self currentRemote] currentSongElapsed],
919 [[self currentRemote] currentSongLength]];
921 [self networkError:localException];
925 if ( [df boolForKey:@"showTrackNumber"] ) {
930 trackNo = [[self currentRemote] currentSongTrack];
931 trackCount = [[self currentRemote] currentAlbumTrackCount];
933 [self networkError:localException];
936 if ( (trackNo > 0) || (trackCount > 0) ) {
937 track = [NSString stringWithFormat:@"%@: %i %@ %i",
938 @"Track", trackNo, @"of", trackCount];
942 if ( [df boolForKey:@"showTrackRating"] ) {
943 float currentRating = 0;
946 currentRating = [[self currentRemote] currentSongRating];
948 [self networkError:localException];
951 if (currentRating >= 0.0) {
952 rating = ( currentRating * 5 );
956 if ( [df boolForKey:@"showPlayCount"] && ![self radioIsPlaying] && [[self currentRemote] currentSource] == ITMTRemoteLibrarySource ) {
958 playCount = [[self currentRemote] currentSongPlayCount];
960 [self networkError:localException];
964 title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
966 ITDebugLog(@"Showing current track info status window.");
967 [statusWindowController showSongInfoWindowWithSource:source
979 - (void)showUpcomingSongs
983 numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
985 [self networkError:localException];
988 ITDebugLog(@"Showing upcoming songs status window.");
991 int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
992 NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
993 int curTrack = [[self currentRemote] currentSongIndex];
996 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
998 [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
1002 if ([songList count] == 0) {
1003 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
1006 [statusWindowController showUpcomingSongsWindowWithTitles:songList];
1008 [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
1011 [self networkError:localException];
1020 NSMenu *menu = [statusItem menu];
1021 [(NSCarbonMenuImpl *)[menu _menuImpl] popUpMenu:menu atLocation:[NSEvent mouseLocation] width:1 forView:nil withSelectedItem:-30 withFont:[NSFont menuFontOfSize:32]];
1026 - (void)incrementVolume
1029 float volume = [[self currentRemote] volume];
1030 float dispVol = volume;
1031 ITDebugLog(@"Incrementing volume.");
1040 ITDebugLog(@"Setting volume to %f", volume);
1041 [[self currentRemote] setVolume:volume];
1043 // Show volume status window
1044 [statusWindowController showVolumeWindowWithLevel:dispVol];
1046 [self networkError:localException];
1050 - (void)decrementVolume
1053 float volume = [[self currentRemote] volume];
1054 float dispVol = volume;
1055 ITDebugLog(@"Decrementing volume.");
1064 ITDebugLog(@"Setting volume to %f", volume);
1065 [[self currentRemote] setVolume:volume];
1067 //Show volume status window
1068 [statusWindowController showVolumeWindowWithLevel:dispVol];
1070 [self networkError:localException];
1074 - (void)incrementRating
1077 float rating = [[self currentRemote] currentSongRating];
1078 ITDebugLog(@"Incrementing rating.");
1080 if ([[self currentRemote] currentPlaylistIndex] == 0) {
1081 ITDebugLog(@"No song playing, rating change aborted.");
1089 ITDebugLog(@"Setting rating to %f", rating);
1090 [[self currentRemote] setCurrentSongRating:rating];
1092 //Show rating status window
1093 [statusWindowController showRatingWindowWithRating:rating];
1095 [self networkError:localException];
1099 - (void)decrementRating
1102 float rating = [[self currentRemote] currentSongRating];
1103 ITDebugLog(@"Decrementing rating.");
1105 if ([[self currentRemote] currentPlaylistIndex] == 0) {
1106 ITDebugLog(@"No song playing, rating change aborted.");
1114 ITDebugLog(@"Setting rating to %f", rating);
1115 [[self currentRemote] setCurrentSongRating:rating];
1117 //Show rating status window
1118 [statusWindowController showRatingWindowWithRating:rating];
1120 [self networkError:localException];
1124 - (void)setRating:(ITHotKey *)sender
1126 int stars = [[sender name] characterAtIndex:9] - 48;
1127 [self selectSongRating:stars * 20];
1128 [statusWindowController showRatingWindowWithRating:(float)stars / 5.0];
1134 ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
1135 ITDebugLog(@"Toggling repeat mode.");
1136 switch (repeatMode) {
1137 case ITMTRemotePlayerRepeatOff:
1138 repeatMode = ITMTRemotePlayerRepeatAll;
1140 case ITMTRemotePlayerRepeatAll:
1141 repeatMode = ITMTRemotePlayerRepeatOne;
1143 case ITMTRemotePlayerRepeatOne:
1144 repeatMode = ITMTRemotePlayerRepeatOff;
1147 ITDebugLog(@"Setting repeat mode to %i", repeatMode);
1148 [[self currentRemote] setRepeatMode:repeatMode];
1150 //Show loop status window
1151 [statusWindowController showRepeatWindowWithMode:repeatMode];
1153 [self networkError:localException];
1157 - (void)toggleShuffle
1160 BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
1161 ITDebugLog(@"Toggling shuffle mode.");
1162 [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
1163 //Show shuffle status window
1164 ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
1165 [statusWindowController showShuffleWindow:newShuffleEnabled];
1167 [self networkError:localException];
1171 - (void)registerNowOK
1173 [[StatusWindow sharedWindow] setLocked:NO];
1174 [[StatusWindow sharedWindow] vanish:self];
1175 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1180 - (void)registerNowCancel
1182 [[StatusWindow sharedWindow] setLocked:NO];
1183 [[StatusWindow sharedWindow] vanish:self];
1184 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1186 [NSApp terminate:self];
1189 /*************************************************************************/
1191 #pragma mark NETWORK HANDLERS
1192 /*************************************************************************/
1194 - (void)setServerStatus:(BOOL)newStatus
1198 [networkController setServerStatus:YES];
1201 [networkController setServerStatus:NO];
1205 - (int)connectToServer
1208 ITDebugLog(@"Attempting to connect to shared remote.");
1209 result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
1212 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1213 currentRemote = [[[networkController networkObject] remote] retain];
1215 [self setupHotKeys];
1216 //playerRunningState = ITMTRemotePlayerRunning;
1217 playerRunningState = [[self currentRemote] playerRunningState];
1219 [refreshTimer invalidate];
1220 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1222 selector:@selector(timerUpdate)
1224 repeats:YES] retain];
1226 ITDebugLog(@"Connection successful.");
1228 } else if (result == 0) {
1229 ITDebugLog(@"Connection failed.");
1230 currentRemote = [remoteArray objectAtIndex:0];
1233 //Do something about the password being invalid
1234 ITDebugLog(@"Connection failed.");
1235 currentRemote = [remoteArray objectAtIndex:0];
1240 - (BOOL)disconnectFromServer
1242 ITDebugLog(@"Disconnecting from shared remote.");
1244 [currentRemote release];
1245 currentRemote = [remoteArray objectAtIndex:0];
1246 [networkController disconnect];
1248 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
1249 [self applicationLaunched:nil];
1251 [self applicationTerminated:nil];
1257 - (void)checkForRemoteServer
1259 [self checkForRemoteServerAndConnectImmediately:NO];
1262 - (void)checkForRemoteServerAndConnectImmediately:(BOOL)connectImmediately
1264 ITDebugLog(@"Checking for remote server.");
1265 if (!_checkingForServer) {
1266 if (!_serverCheckLock) {
1267 _serverCheckLock = [[NSLock alloc] init];
1269 [_serverCheckLock lock];
1270 _checkingForServer = YES;
1271 [_serverCheckLock unlock];
1272 [NSThread detachNewThreadSelector:@selector(runRemoteServerCheck:) toTarget:self withObject:[NSNumber numberWithBool:connectImmediately]];
1276 - (void)runRemoteServerCheck:(id)sender
1278 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1279 ITDebugLog(@"Remote server check running.");
1280 if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1281 ITDebugLog(@"Remote server found.");
1282 if ([sender boolValue]) {
1283 [self performSelectorOnMainThread:@selector(connectToServer) withObject:nil waitUntilDone:NO];
1285 [self performSelectorOnMainThread:@selector(remoteServerFound:) withObject:nil waitUntilDone:NO];
1288 ITDebugLog(@"Remote server not found.");
1289 [self performSelectorOnMainThread:@selector(remoteServerNotFound:) withObject:nil waitUntilDone:NO];
1291 [_serverCheckLock lock];
1292 _checkingForServer = NO;
1293 [_serverCheckLock unlock];
1297 - (void)remoteServerFound:(id)sender
1299 if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1300 [[StatusWindowController sharedController] showReconnectQueryWindow];
1304 - (void)remoteServerNotFound:(id)sender
1306 if (![[NetworkController sharedController] isConnectedToServer]) {
1307 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1311 - (void)networkError:(NSException *)exception
1313 ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1314 if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1315 //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);
1316 [[StatusWindowController sharedController] showNetworkErrorQueryWindow];
1317 if ([self disconnectFromServer]) {
1318 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1319 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1321 ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1328 /*if ([self connectToServer] == 0) {
1329 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1331 [self checkForRemoteServerAndConnectImmediately:YES];
1332 [[StatusWindow sharedWindow] setLocked:NO];
1333 [[StatusWindow sharedWindow] vanish:self];
1334 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1337 - (void)cancelReconnect
1339 [[StatusWindow sharedWindow] setLocked:NO];
1340 [[StatusWindow sharedWindow] vanish:self];
1341 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1344 /*************************************************************************/
1346 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1347 /*************************************************************************/
1349 - (void)applicationLaunched:(NSNotification *)note
1352 if (!note || ([[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer])) {
1353 ITDebugLog(@"Remote application launched.");
1354 playerRunningState = ITMTRemotePlayerRunning;
1355 [[self currentRemote] begin];
1356 [self setLatestSongIdentifier:@""];
1358 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1360 selector:@selector(timerUpdate)
1362 repeats:YES] retain];
1363 //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1364 [self setupHotKeys];
1367 [self networkError:localException];
1371 - (void)applicationTerminated:(NSNotification *)note
1374 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer]) {
1375 ITDebugLog(@"Remote application terminated.");
1376 playerRunningState = ITMTRemotePlayerNotRunning;
1377 [[self currentRemote] halt];
1378 [refreshTimer invalidate];
1379 [refreshTimer release];
1381 [self clearHotKeys];
1383 if ([df objectForKey:@"ShowPlayer"] != nil) {
1385 ITDebugLog(@"Setting up show player hot key.");
1386 hotKey = [[ITHotKey alloc] init];
1387 [hotKey setName:@"ShowPlayer"];
1388 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1389 [hotKey setTarget:self];
1390 [hotKey setAction:@selector(showPlayer)];
1391 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1395 [self networkError:localException];
1400 /*************************************************************************/
1402 #pragma mark NSApplication DELEGATE METHODS
1403 /*************************************************************************/
1405 - (void)applicationWillTerminate:(NSNotification *)note
1407 [networkController stopRemoteServerSearch];
1408 [self clearHotKeys];
1409 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1413 /*************************************************************************/
1415 #pragma mark DEALLOCATION METHOD
1416 /*************************************************************************/
1420 [self applicationTerminated:nil];
1422 [statusItem release];
1423 [statusWindowController release];
1424 [menuController release];
1425 [networkController release];
1426 [_serverCheckLock release];