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 songChanged] && (timerUpdating != YES) && (playerRunningState == ITMTRemotePlayerRunning) ) {
361 ITDebugLog(@"The song changed.");
363 if ([df boolForKey:@"runScripts"]) {
364 NSArray *scripts = [[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"]];
365 NSEnumerator *scriptsEnum = [scripts objectEnumerator];
366 NSString *nextScript;
367 ITDebugLog(@"Running AppleScripts for song change.");
368 while ( (nextScript = [scriptsEnum nextObject]) ) {
370 NSAppleScript *currentScript = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"] stringByAppendingPathComponent:nextScript]] error:&error];
371 ITDebugLog(@"Running script: %@", nextScript);
372 if (!currentScript || ![currentScript executeAndReturnError:nil]) {
373 ITDebugLog(@"Error running script %@.", nextScript);
375 [currentScript release];
380 [statusItem setEnabled:NO];
383 latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
384 [menuController rebuildSubmenus];
386 if ( [df boolForKey:@"showSongInfoOnChange"] ) {
387 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
390 [self setLatestSongIdentifier:[[self currentRemote] playerStateUniqueIdentifier]];
392 //Create the tooltip for the status item
393 if ( [df boolForKey:@"showToolTip"] ) {
394 NSString *artist = [[self currentRemote] currentSongArtist];
395 NSString *title = [[self currentRemote] currentSongTitle];
397 ITDebugLog(@"Creating status item tooltip.");
399 toolTip = [NSString stringWithFormat:@"%@ - %@", artist, title];
403 toolTip = @"No Song Playing";
405 [statusItem setToolTip:toolTip];
407 [statusItem setToolTip:nil];
410 [self networkError:localException];
414 [statusItem setEnabled:YES];
417 if ([networkController isConnectedToServer]) {
418 [statusItem setMenu:([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) ? [menuController menu] : [menuController menuForNoPlayer]];
424 ITDebugLog(@"Menu clicked.");
425 if ([networkController isConnectedToServer]) {
426 //Used the cached version
431 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
432 [statusItem setMenu:[menuController menu]];
434 [statusItem setMenu:[menuController menuForNoPlayer]];
437 [self networkError:localException];
450 ITMTRemotePlayerPlayingState state = [[self currentRemote] playerPlayingState];
451 ITDebugLog(@"Play/Pause toggled");
452 if (state == ITMTRemotePlayerPlaying) {
453 [[self currentRemote] pause];
454 } else if ((state == ITMTRemotePlayerForwarding) || (state == ITMTRemotePlayerRewinding)) {
455 [[self currentRemote] pause];
456 [[self currentRemote] play];
458 [[self currentRemote] play];
461 [self networkError:localException];
469 ITDebugLog(@"Going to next song.");
471 [[self currentRemote] goToNextSong];
473 [self networkError:localException];
480 ITDebugLog(@"Going to previous song.");
482 [[self currentRemote] goToPreviousSong];
484 [self networkError:localException];
491 ITDebugLog(@"Fast forwarding.");
493 [[self currentRemote] forward];
495 [self networkError:localException];
502 ITDebugLog(@"Rewinding.");
504 [[self currentRemote] rewind];
506 [self networkError:localException];
511 - (void)selectPlaylistAtIndex:(int)index
513 ITDebugLog(@"Selecting playlist %i", index);
515 [[self currentRemote] switchToPlaylistAtIndex:(index % 1000) ofSourceAtIndex:(index / 1000)];
516 //[[self currentRemote] switchToPlaylistAtIndex:index];
518 [self networkError:localException];
523 - (void)selectSongAtIndex:(int)index
525 ITDebugLog(@"Selecting song %i", index);
527 [[self currentRemote] switchToSongAtIndex:index];
529 [self networkError:localException];
534 - (void)selectSongRating:(int)rating
536 ITDebugLog(@"Selecting song rating %i", rating);
538 [[self currentRemote] setCurrentSongRating:(float)rating / 100.0];
540 [self networkError:localException];
545 - (void)selectEQPresetAtIndex:(int)index
547 ITDebugLog(@"Selecting EQ preset %i", index);
550 [[self currentRemote] setEqualizerEnabled:![[self currentRemote] equalizerEnabled]];
552 [[self currentRemote] switchToEQAtIndex:index];
555 [self networkError:localException];
562 ITDebugLog(@"Beginning show player.");
563 //if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
564 ITDebugLog(@"Showing player interface.");
566 [[self currentRemote] showPrimaryInterface];
568 [self networkError:localException];
571 ITDebugLog(@"Launching player.");
574 if ( (path = [df stringForKey:@"CustomPlayerPath"]) ) {
576 pathITDebugLog(@"Showing player interface."); = [[self currentRemote] playerFullName];
578 if (![[NSWorkspace sharedWorkspace] launchApplication:path]) {
579 ITDebugLog(@"Error Launching Player");
582 [self networkError:localException];
585 ITDebugLog(@"Finished show player.");
588 - (void)showPreferences
590 ITDebugLog(@"Show preferences.");
591 [[PreferencesController sharedPrefs] showPrefsWindow:self];
594 - (void)showPreferencesAndClose
596 ITDebugLog(@"Show preferences.");
597 [[PreferencesController sharedPrefs] showPrefsWindow:self];
598 [[StatusWindow sharedWindow] setLocked:NO];
599 [[StatusWindow sharedWindow] vanish:self];
600 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
603 - (void)showTestWindow
605 [self showCurrentTrackInfo];
608 - (void)quitMenuTunes
610 ITDebugLog(@"Quitting MenuTunes.");
611 [NSApp terminate:self];
617 - (MenuController *)menuController
619 return menuController;
622 - (void)closePreferences
624 ITDebugLog(@"Preferences closed.");
625 if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
630 - (ITMTRemote *)currentRemote
632 if ([networkController isConnectedToServer] && ![[networkController networkObject] isValid]) {
633 [self networkError:nil];
636 return currentRemote;
647 NSEnumerator *hotKeyEnumerator = [[[ITHotKeyCenter sharedCenter] allHotKeys] objectEnumerator];
648 ITHotKey *nextHotKey;
649 ITDebugLog(@"Clearing hot keys.");
650 while ( (nextHotKey = [hotKeyEnumerator nextObject]) ) {
651 [[ITHotKeyCenter sharedCenter] unregisterHotKey:nextHotKey];
653 ITDebugLog(@"Done clearing hot keys.");
659 ITDebugLog(@"Setting up hot keys.");
661 if (playerRunningState == ITMTRemotePlayerNotRunning && ![[NetworkController sharedController] isConnectedToServer]) {
665 if ([df objectForKey:@"PlayPause"] != nil) {
666 ITDebugLog(@"Setting up play pause hot key.");
667 hotKey = [[ITHotKey alloc] init];
668 [hotKey setName:@"PlayPause"];
669 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PlayPause"]]];
670 [hotKey setTarget:self];
671 [hotKey setAction:@selector(playPause)];
672 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
675 if ([df objectForKey:@"NextTrack"] != nil) {
676 ITDebugLog(@"Setting up next track hot key.");
677 hotKey = [[ITHotKey alloc] init];
678 [hotKey setName:@"NextTrack"];
679 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"NextTrack"]]];
680 [hotKey setTarget:self];
681 [hotKey setAction:@selector(nextSong)];
682 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
685 if ([df objectForKey:@"PrevTrack"] != nil) {
686 ITDebugLog(@"Setting up previous track hot key.");
687 hotKey = [[ITHotKey alloc] init];
688 [hotKey setName:@"PrevTrack"];
689 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PrevTrack"]]];
690 [hotKey setTarget:self];
691 [hotKey setAction:@selector(prevSong)];
692 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
695 if ([df objectForKey:@"FastForward"] != nil) {
696 ITDebugLog(@"Setting up fast forward hot key.");
697 hotKey = [[ITHotKey alloc] init];
698 [hotKey setName:@"FastForward"];
699 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"FastForward"]]];
700 [hotKey setTarget:self];
701 [hotKey setAction:@selector(fastForward)];
702 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
705 if ([df objectForKey:@"Rewind"] != nil) {
706 ITDebugLog(@"Setting up rewind hot key.");
707 hotKey = [[ITHotKey alloc] init];
708 [hotKey setName:@"Rewind"];
709 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"Rewind"]]];
710 [hotKey setTarget:self];
711 [hotKey setAction:@selector(rewind)];
712 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
715 if ([df objectForKey:@"ShowPlayer"] != nil) {
716 ITDebugLog(@"Setting up show player hot key.");
717 hotKey = [[ITHotKey alloc] init];
718 [hotKey setName:@"ShowPlayer"];
719 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
720 [hotKey setTarget:self];
721 [hotKey setAction:@selector(showPlayer)];
722 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
725 if ([df objectForKey:@"TrackInfo"] != nil) {
726 ITDebugLog(@"Setting up track info hot key.");
727 hotKey = [[ITHotKey alloc] init];
728 [hotKey setName:@"TrackInfo"];
729 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"TrackInfo"]]];
730 [hotKey setTarget:self];
731 [hotKey setAction:@selector(showCurrentTrackInfo)];
732 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
735 if ([df objectForKey:@"UpcomingSongs"] != nil) {
736 ITDebugLog(@"Setting up upcoming songs hot key.");
737 hotKey = [[ITHotKey alloc] init];
738 [hotKey setName:@"UpcomingSongs"];
739 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"UpcomingSongs"]]];
740 [hotKey setTarget:self];
741 [hotKey setAction:@selector(showUpcomingSongs)];
742 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
745 if ([df objectForKey:@"ToggleLoop"] != nil) {
746 ITDebugLog(@"Setting up toggle loop hot key.");
747 hotKey = [[ITHotKey alloc] init];
748 [hotKey setName:@"ToggleLoop"];
749 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleLoop"]]];
750 [hotKey setTarget:self];
751 [hotKey setAction:@selector(toggleLoop)];
752 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
755 if ([df objectForKey:@"ToggleShuffle"] != nil) {
756 ITDebugLog(@"Setting up toggle shuffle hot key.");
757 hotKey = [[ITHotKey alloc] init];
758 [hotKey setName:@"ToggleShuffle"];
759 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShuffle"]]];
760 [hotKey setTarget:self];
761 [hotKey setAction:@selector(toggleShuffle)];
762 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
765 if ([df objectForKey:@"IncrementVolume"] != nil) {
766 ITDebugLog(@"Setting up increment volume hot key.");
767 hotKey = [[ITHotKey alloc] init];
768 [hotKey setName:@"IncrementVolume"];
769 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementVolume"]]];
770 [hotKey setTarget:self];
771 [hotKey setAction:@selector(incrementVolume)];
772 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
775 if ([df objectForKey:@"DecrementVolume"] != nil) {
776 ITDebugLog(@"Setting up decrement volume hot key.");
777 hotKey = [[ITHotKey alloc] init];
778 [hotKey setName:@"DecrementVolume"];
779 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementVolume"]]];
780 [hotKey setTarget:self];
781 [hotKey setAction:@selector(decrementVolume)];
782 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
785 if ([df objectForKey:@"IncrementRating"] != nil) {
786 ITDebugLog(@"Setting up increment rating hot key.");
787 hotKey = [[ITHotKey alloc] init];
788 [hotKey setName:@"IncrementRating"];
789 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementRating"]]];
790 [hotKey setTarget:self];
791 [hotKey setAction:@selector(incrementRating)];
792 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
795 if ([df objectForKey:@"DecrementRating"] != nil) {
796 ITDebugLog(@"Setting up decrement rating hot key.");
797 hotKey = [[ITHotKey alloc] init];
798 [hotKey setName:@"DecrementRating"];
799 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementRating"]]];
800 [hotKey setTarget:self];
801 [hotKey setAction:@selector(decrementRating)];
802 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
805 if ([df objectForKey:@"PopupMenu"] != nil) {
806 ITDebugLog(@"Setting up popup menu hot key.");
807 hotKey = [[ITHotKey alloc] init];
808 [hotKey setName:@"PopupMenu"];
809 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PopupMenu"]]];
810 [hotKey setTarget:self];
811 [hotKey setAction:@selector(popupMenu)];
812 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
816 for (i = 0; i <= 5; i++) {
817 NSString *curName = [NSString stringWithFormat:@"SetRating%i", i];
818 if ([df objectForKey:curName] != nil) {
819 ITDebugLog(@"Setting up set rating %i hot key.", i);
820 hotKey = [[ITHotKey alloc] init];
821 [hotKey setName:curName];
822 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:curName]]];
823 [hotKey setTarget:self];
824 [hotKey setAction:@selector(setRating:)];
825 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
828 ITDebugLog(@"Finished setting up hot keys.");
831 - (void)showCurrentTrackInfo
833 ITMTRemotePlayerSource source = 0;
834 NSString *title = nil;
835 NSString *album = nil;
836 NSString *artist = nil;
837 NSString *composer = nil;
838 NSString *time = nil;
839 NSString *track = nil;
844 ITDebugLog(@"Showing track info status window.");
847 source = [[self currentRemote] currentSource];
848 title = [[self currentRemote] currentSongTitle];
850 [self networkError:localException];
854 if ( [df boolForKey:@"showAlbumArtwork"] ) {
855 NSSize oldSize, newSize;
857 art = [[self currentRemote] currentSongAlbumArt];
858 oldSize = [art size];
859 if (oldSize.width > oldSize.height) newSize = NSMakeSize(110,oldSize.height * (110.0f / oldSize.width));
860 else newSize = NSMakeSize(oldSize.width * (110.0f / oldSize.height),110);
861 art = [[[[NSImage alloc] initWithData:[art TIFFRepresentation]] autorelease] imageScaledSmoothlyToSize:newSize];
863 [self networkError:localException];
867 if ( [df boolForKey:@"showAlbum"] ) {
869 album = [[self currentRemote] currentSongAlbum];
871 [self networkError:localException];
875 if ( [df boolForKey:@"showArtist"] ) {
877 artist = [[self currentRemote] currentSongArtist];
879 [self networkError:localException];
883 if ( [df boolForKey:@"showComposer"] ) {
885 composer = [[self currentRemote] currentSongComposer];
887 [self networkError:localException];
891 if ( [df boolForKey:@"showTime"] ) {
893 time = [NSString stringWithFormat:@"%@: %@ / %@",
894 NSLocalizedString(@"time", @"Time"),
895 [[self currentRemote] currentSongElapsed],
896 [[self currentRemote] currentSongLength]];
898 [self networkError:localException];
902 if ( [df boolForKey:@"showTrackNumber"] ) {
907 trackNo = [[self currentRemote] currentSongTrack];
908 trackCount = [[self currentRemote] currentAlbumTrackCount];
910 [self networkError:localException];
913 if ( (trackNo > 0) || (trackCount > 0) ) {
914 track = [NSString stringWithFormat:@"%@: %i %@ %i",
915 @"Track", trackNo, @"of", trackCount];
919 if ( [df boolForKey:@"showTrackRating"] ) {
920 float currentRating = 0;
923 currentRating = [[self currentRemote] currentSongRating];
925 [self networkError:localException];
928 if (currentRating >= 0.0) {
929 rating = ( currentRating * 5 );
933 if ( [df boolForKey:@"showPlayCount"] && ![self radioIsPlaying] ) {
935 playCount = [[self currentRemote] currentSongPlayCount];
937 [self networkError:localException];
941 title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
943 ITDebugLog(@"Showing current track info status window.");
944 [statusWindowController showSongInfoWindowWithSource:source
956 - (void)showUpcomingSongs
960 numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
962 [self networkError:localException];
965 ITDebugLog(@"Showing upcoming songs status window.");
968 int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
969 NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
970 int curTrack = [[self currentRemote] currentSongIndex];
973 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
975 [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
979 if ([songList count] == 0) {
980 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
983 [statusWindowController showUpcomingSongsWindowWithTitles:songList];
985 [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
988 [self networkError:localException];
995 NSMenu *menu = [menuController menu];
997 [(NSCarbonMenuImpl *)[menu _menuImpl] popUpMenu:menu atLocation:[NSEvent mouseLocation] width:1 forView:nil withSelectedItem:-30 withFont:[NSFont menuFontOfSize:32]];
1002 - (void)incrementVolume
1005 float volume = [[self currentRemote] volume];
1006 float dispVol = volume;
1007 ITDebugLog(@"Incrementing volume.");
1016 ITDebugLog(@"Setting volume to %f", volume);
1017 [[self currentRemote] setVolume:volume];
1019 // Show volume status window
1020 [statusWindowController showVolumeWindowWithLevel:dispVol];
1022 [self networkError:localException];
1026 - (void)decrementVolume
1029 float volume = [[self currentRemote] volume];
1030 float dispVol = volume;
1031 ITDebugLog(@"Decrementing 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)incrementRating
1053 float rating = [[self currentRemote] currentSongRating];
1054 ITDebugLog(@"Incrementing rating.");
1056 if ([[self currentRemote] currentPlaylistIndex] == 0) {
1057 ITDebugLog(@"No song playing, rating change aborted.");
1065 ITDebugLog(@"Setting rating to %f", rating);
1066 [[self currentRemote] setCurrentSongRating:rating];
1068 //Show rating status window
1069 [statusWindowController showRatingWindowWithRating:rating];
1071 [self networkError:localException];
1075 - (void)decrementRating
1078 float rating = [[self currentRemote] currentSongRating];
1079 ITDebugLog(@"Decrementing rating.");
1081 if ([[self currentRemote] currentPlaylistIndex] == 0) {
1082 ITDebugLog(@"No song playing, rating change aborted.");
1090 ITDebugLog(@"Setting rating to %f", rating);
1091 [[self currentRemote] setCurrentSongRating:rating];
1093 //Show rating status window
1094 [statusWindowController showRatingWindowWithRating:rating];
1096 [self networkError:localException];
1100 - (void)setRating:(ITHotKey *)sender
1102 int stars = [[sender name] characterAtIndex:9] - 48;
1103 [self selectSongRating:stars * 20];
1104 [statusWindowController showRatingWindowWithRating:(float)stars / 5.0];
1110 ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
1111 ITDebugLog(@"Toggling repeat mode.");
1112 switch (repeatMode) {
1113 case ITMTRemotePlayerRepeatOff:
1114 repeatMode = ITMTRemotePlayerRepeatAll;
1116 case ITMTRemotePlayerRepeatAll:
1117 repeatMode = ITMTRemotePlayerRepeatOne;
1119 case ITMTRemotePlayerRepeatOne:
1120 repeatMode = ITMTRemotePlayerRepeatOff;
1123 ITDebugLog(@"Setting repeat mode to %i", repeatMode);
1124 [[self currentRemote] setRepeatMode:repeatMode];
1126 //Show loop status window
1127 [statusWindowController showRepeatWindowWithMode:repeatMode];
1129 [self networkError:localException];
1133 - (void)toggleShuffle
1136 BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
1137 ITDebugLog(@"Toggling shuffle mode.");
1138 [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
1139 //Show shuffle status window
1140 ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
1141 [statusWindowController showShuffleWindow:newShuffleEnabled];
1143 [self networkError:localException];
1147 - (void)registerNowOK
1149 [[StatusWindow sharedWindow] setLocked:NO];
1150 [[StatusWindow sharedWindow] vanish:self];
1151 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1156 - (void)registerNowCancel
1158 [[StatusWindow sharedWindow] setLocked:NO];
1159 [[StatusWindow sharedWindow] vanish:self];
1160 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1162 [NSApp terminate:self];
1165 /*************************************************************************/
1167 #pragma mark NETWORK HANDLERS
1168 /*************************************************************************/
1170 - (void)setServerStatus:(BOOL)newStatus
1174 [networkController setServerStatus:YES];
1177 [networkController setServerStatus:NO];
1181 - (int)connectToServer
1184 ITDebugLog(@"Attempting to connect to shared remote.");
1185 result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
1188 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1189 currentRemote = [[[networkController networkObject] remote] retain];
1191 [self setupHotKeys];
1192 //playerRunningState = ITMTRemotePlayerRunning;
1193 playerRunningState = [[self currentRemote] playerRunningState];
1195 [refreshTimer invalidate];
1196 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1198 selector:@selector(timerUpdate)
1200 repeats:YES] retain];
1202 ITDebugLog(@"Connection successful.");
1204 } else if (result == 0) {
1205 ITDebugLog(@"Connection failed.");
1206 currentRemote = [remoteArray objectAtIndex:0];
1209 //Do something about the password being invalid
1210 ITDebugLog(@"Connection failed.");
1211 currentRemote = [remoteArray objectAtIndex:0];
1216 - (BOOL)disconnectFromServer
1218 ITDebugLog(@"Disconnecting from shared remote.");
1220 [currentRemote release];
1221 currentRemote = [remoteArray objectAtIndex:0];
1222 [networkController disconnect];
1224 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
1225 [self applicationLaunched:nil];
1227 [self applicationTerminated:nil];
1233 - (void)checkForRemoteServer
1235 [self checkForRemoteServerAndConnectImmediately:NO];
1238 - (void)checkForRemoteServerAndConnectImmediately:(BOOL)connectImmediately
1240 ITDebugLog(@"Checking for remote server.");
1241 if (!_checkingForServer) {
1242 if (!_serverCheckLock) {
1243 _serverCheckLock = [[NSLock alloc] init];
1245 [_serverCheckLock lock];
1246 _checkingForServer = YES;
1247 [_serverCheckLock unlock];
1248 [NSThread detachNewThreadSelector:@selector(runRemoteServerCheck:) toTarget:self withObject:[NSNumber numberWithBool:connectImmediately]];
1252 - (void)runRemoteServerCheck:(id)sender
1254 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1255 ITDebugLog(@"Remote server check running.");
1256 if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1257 ITDebugLog(@"Remote server found.");
1258 if ([sender boolValue]) {
1259 [self performSelectorOnMainThread:@selector(connectToServer) withObject:nil waitUntilDone:NO];
1261 [self performSelectorOnMainThread:@selector(remoteServerFound:) withObject:nil waitUntilDone:NO];
1264 ITDebugLog(@"Remote server not found.");
1265 [self performSelectorOnMainThread:@selector(remoteServerNotFound:) withObject:nil waitUntilDone:NO];
1267 [_serverCheckLock lock];
1268 _checkingForServer = NO;
1269 [_serverCheckLock unlock];
1273 - (void)remoteServerFound:(id)sender
1275 if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1276 [[StatusWindowController sharedController] showReconnectQueryWindow];
1280 - (void)remoteServerNotFound:(id)sender
1282 if (![[NetworkController sharedController] isConnectedToServer]) {
1283 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1287 - (void)networkError:(NSException *)exception
1289 ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1290 if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1291 //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);
1292 [[StatusWindowController sharedController] showNetworkErrorQueryWindow];
1293 if ([self disconnectFromServer]) {
1294 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1295 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1297 ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1304 /*if ([self connectToServer] == 0) {
1305 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1307 [self checkForRemoteServerAndConnectImmediately:YES];
1308 [[StatusWindow sharedWindow] setLocked:NO];
1309 [[StatusWindow sharedWindow] vanish:self];
1310 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1313 - (void)cancelReconnect
1315 [[StatusWindow sharedWindow] setLocked:NO];
1316 [[StatusWindow sharedWindow] vanish:self];
1317 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1320 /*************************************************************************/
1322 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1323 /*************************************************************************/
1325 - (void)applicationLaunched:(NSNotification *)note
1328 if (!note || ([[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer])) {
1329 ITDebugLog(@"Remote application launched.");
1330 playerRunningState = ITMTRemotePlayerRunning;
1331 [[self currentRemote] begin];
1332 [self setLatestSongIdentifier:@""];
1334 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1336 selector:@selector(timerUpdate)
1338 repeats:YES] retain];
1339 //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1340 [self setupHotKeys];
1343 [self networkError:localException];
1347 - (void)applicationTerminated:(NSNotification *)note
1350 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer]) {
1351 ITDebugLog(@"Remote application terminated.");
1352 playerRunningState = ITMTRemotePlayerNotRunning;
1353 [[self currentRemote] halt];
1354 [refreshTimer invalidate];
1355 [refreshTimer release];
1357 [self clearHotKeys];
1359 if ([df objectForKey:@"ShowPlayer"] != nil) {
1361 ITDebugLog(@"Setting up show player hot key.");
1362 hotKey = [[ITHotKey alloc] init];
1363 [hotKey setName:@"ShowPlayer"];
1364 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1365 [hotKey setTarget:self];
1366 [hotKey setAction:@selector(showPlayer)];
1367 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1371 [self networkError:localException];
1376 /*************************************************************************/
1378 #pragma mark NSApplication DELEGATE METHODS
1379 /*************************************************************************/
1381 - (void)applicationWillTerminate:(NSNotification *)note
1383 [networkController stopRemoteServerSearch];
1384 [self clearHotKeys];
1385 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1389 /*************************************************************************/
1391 #pragma mark DEALLOCATION METHOD
1392 /*************************************************************************/
1396 [self applicationTerminated:nil];
1398 [statusItem release];
1399 [statusWindowController release];
1400 [menuController release];
1401 [networkController release];
1402 [_serverCheckLock release];