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.");
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];
559 - (void)makePlaylistWithTerm:(NSString *)term ofType:(int)type
561 ITDebugLog(@"Making playlist with term %@, type %i", term, type);
563 [[self currentRemote] makePlaylistWithTerm:term ofType:type];
565 [self networkError:localException];
567 ITDebugLog(@"Done making playlist");
572 ITDebugLog(@"Beginning show player.");
573 //if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
574 ITDebugLog(@"Showing player interface.");
576 [[self currentRemote] showPrimaryInterface];
578 [self networkError:localException];
581 ITDebugLog(@"Launching player.");
584 if ( (path = [df stringForKey:@"CustomPlayerPath"]) ) {
586 pathITDebugLog(@"Showing player interface."); = [[self currentRemote] playerFullName];
588 if (![[NSWorkspace sharedWorkspace] launchApplication:path]) {
589 ITDebugLog(@"Error Launching Player");
592 [self networkError:localException];
595 ITDebugLog(@"Finished show player.");
598 - (void)showPreferences
600 ITDebugLog(@"Show preferences.");
601 [[PreferencesController sharedPrefs] showPrefsWindow:self];
604 - (void)showPreferencesAndClose
606 ITDebugLog(@"Show preferences.");
607 [[PreferencesController sharedPrefs] showPrefsWindow:self];
608 [[StatusWindow sharedWindow] setLocked:NO];
609 [[StatusWindow sharedWindow] vanish:self];
610 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
613 - (void)showTestWindow
615 [self showCurrentTrackInfo];
618 - (void)quitMenuTunes
620 ITDebugLog(@"Quitting MenuTunes.");
621 [NSApp terminate:self];
627 - (MenuController *)menuController
629 return menuController;
632 - (void)closePreferences
634 ITDebugLog(@"Preferences closed.");
635 if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
640 - (ITMTRemote *)currentRemote
642 if ([networkController isConnectedToServer] && ![[networkController networkObject] isValid]) {
643 [self networkError:nil];
646 return currentRemote;
657 NSEnumerator *hotKeyEnumerator = [[[ITHotKeyCenter sharedCenter] allHotKeys] objectEnumerator];
658 ITHotKey *nextHotKey;
659 ITDebugLog(@"Clearing hot keys.");
660 while ( (nextHotKey = [hotKeyEnumerator nextObject]) ) {
661 [[ITHotKeyCenter sharedCenter] unregisterHotKey:nextHotKey];
663 ITDebugLog(@"Done clearing hot keys.");
669 ITDebugLog(@"Setting up hot keys.");
671 if (playerRunningState == ITMTRemotePlayerNotRunning && ![[NetworkController sharedController] isConnectedToServer]) {
675 if ([df objectForKey:@"PlayPause"] != nil) {
676 ITDebugLog(@"Setting up play pause hot key.");
677 hotKey = [[ITHotKey alloc] init];
678 [hotKey setName:@"PlayPause"];
679 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PlayPause"]]];
680 [hotKey setTarget:self];
681 [hotKey setAction:@selector(playPause)];
682 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
685 if ([df objectForKey:@"NextTrack"] != nil) {
686 ITDebugLog(@"Setting up next track hot key.");
687 hotKey = [[ITHotKey alloc] init];
688 [hotKey setName:@"NextTrack"];
689 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"NextTrack"]]];
690 [hotKey setTarget:self];
691 [hotKey setAction:@selector(nextSong)];
692 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
695 if ([df objectForKey:@"PrevTrack"] != nil) {
696 ITDebugLog(@"Setting up previous track hot key.");
697 hotKey = [[ITHotKey alloc] init];
698 [hotKey setName:@"PrevTrack"];
699 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PrevTrack"]]];
700 [hotKey setTarget:self];
701 [hotKey setAction:@selector(prevSong)];
702 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
705 if ([df objectForKey:@"FastForward"] != nil) {
706 ITDebugLog(@"Setting up fast forward hot key.");
707 hotKey = [[ITHotKey alloc] init];
708 [hotKey setName:@"FastForward"];
709 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"FastForward"]]];
710 [hotKey setTarget:self];
711 [hotKey setAction:@selector(fastForward)];
712 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
715 if ([df objectForKey:@"Rewind"] != nil) {
716 ITDebugLog(@"Setting up rewind hot key.");
717 hotKey = [[ITHotKey alloc] init];
718 [hotKey setName:@"Rewind"];
719 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"Rewind"]]];
720 [hotKey setTarget:self];
721 [hotKey setAction:@selector(rewind)];
722 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
725 if ([df objectForKey:@"ShowPlayer"] != nil) {
726 ITDebugLog(@"Setting up show player hot key.");
727 hotKey = [[ITHotKey alloc] init];
728 [hotKey setName:@"ShowPlayer"];
729 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
730 [hotKey setTarget:self];
731 [hotKey setAction:@selector(showPlayer)];
732 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
735 if ([df objectForKey:@"TrackInfo"] != nil) {
736 ITDebugLog(@"Setting up track info hot key.");
737 hotKey = [[ITHotKey alloc] init];
738 [hotKey setName:@"TrackInfo"];
739 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"TrackInfo"]]];
740 [hotKey setTarget:self];
741 [hotKey setAction:@selector(showCurrentTrackInfo)];
742 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
745 if ([df objectForKey:@"UpcomingSongs"] != nil) {
746 ITDebugLog(@"Setting up upcoming songs hot key.");
747 hotKey = [[ITHotKey alloc] init];
748 [hotKey setName:@"UpcomingSongs"];
749 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"UpcomingSongs"]]];
750 [hotKey setTarget:self];
751 [hotKey setAction:@selector(showUpcomingSongs)];
752 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
755 if ([df objectForKey:@"ToggleLoop"] != nil) {
756 ITDebugLog(@"Setting up toggle loop hot key.");
757 hotKey = [[ITHotKey alloc] init];
758 [hotKey setName:@"ToggleLoop"];
759 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleLoop"]]];
760 [hotKey setTarget:self];
761 [hotKey setAction:@selector(toggleLoop)];
762 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
765 if ([df objectForKey:@"ToggleShuffle"] != nil) {
766 ITDebugLog(@"Setting up toggle shuffle hot key.");
767 hotKey = [[ITHotKey alloc] init];
768 [hotKey setName:@"ToggleShuffle"];
769 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShuffle"]]];
770 [hotKey setTarget:self];
771 [hotKey setAction:@selector(toggleShuffle)];
772 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
775 if ([df objectForKey:@"IncrementVolume"] != nil) {
776 ITDebugLog(@"Setting up increment volume hot key.");
777 hotKey = [[ITHotKey alloc] init];
778 [hotKey setName:@"IncrementVolume"];
779 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementVolume"]]];
780 [hotKey setTarget:self];
781 [hotKey setAction:@selector(incrementVolume)];
782 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
785 if ([df objectForKey:@"DecrementVolume"] != nil) {
786 ITDebugLog(@"Setting up decrement volume hot key.");
787 hotKey = [[ITHotKey alloc] init];
788 [hotKey setName:@"DecrementVolume"];
789 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementVolume"]]];
790 [hotKey setTarget:self];
791 [hotKey setAction:@selector(decrementVolume)];
792 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
795 if ([df objectForKey:@"IncrementRating"] != nil) {
796 ITDebugLog(@"Setting up increment rating hot key.");
797 hotKey = [[ITHotKey alloc] init];
798 [hotKey setName:@"IncrementRating"];
799 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementRating"]]];
800 [hotKey setTarget:self];
801 [hotKey setAction:@selector(incrementRating)];
802 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
805 if ([df objectForKey:@"DecrementRating"] != nil) {
806 ITDebugLog(@"Setting up decrement rating hot key.");
807 hotKey = [[ITHotKey alloc] init];
808 [hotKey setName:@"DecrementRating"];
809 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementRating"]]];
810 [hotKey setTarget:self];
811 [hotKey setAction:@selector(decrementRating)];
812 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
815 if ([df objectForKey:@"PopupMenu"] != nil) {
816 ITDebugLog(@"Setting up popup menu hot key.");
817 hotKey = [[ITHotKey alloc] init];
818 [hotKey setName:@"PopupMenu"];
819 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PopupMenu"]]];
820 [hotKey setTarget:self];
821 [hotKey setAction:@selector(popupMenu)];
822 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
826 for (i = 0; i <= 5; i++) {
827 NSString *curName = [NSString stringWithFormat:@"SetRating%i", i];
828 if ([df objectForKey:curName] != nil) {
829 ITDebugLog(@"Setting up set rating %i hot key.", i);
830 hotKey = [[ITHotKey alloc] init];
831 [hotKey setName:curName];
832 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:curName]]];
833 [hotKey setTarget:self];
834 [hotKey setAction:@selector(setRating:)];
835 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
838 ITDebugLog(@"Finished setting up hot keys.");
841 - (void)showCurrentTrackInfo
843 ITMTRemotePlayerSource source = 0;
844 NSString *title = nil;
845 NSString *album = nil;
846 NSString *artist = nil;
847 NSString *composer = nil;
848 NSString *time = nil;
849 NSString *track = nil;
854 ITDebugLog(@"Showing track info status window.");
857 source = [[self currentRemote] currentSource];
858 title = [[self currentRemote] currentSongTitle];
860 [self networkError:localException];
864 if ( [df boolForKey:@"showAlbumArtwork"] ) {
865 NSSize oldSize, newSize;
867 art = [[self currentRemote] currentSongAlbumArt];
868 oldSize = [art size];
869 if (oldSize.width > oldSize.height) newSize = NSMakeSize(110,oldSize.height * (110.0f / oldSize.width));
870 else newSize = NSMakeSize(oldSize.width * (110.0f / oldSize.height),110);
871 art = [[[[NSImage alloc] initWithData:[art TIFFRepresentation]] autorelease] imageScaledSmoothlyToSize:newSize];
873 [self networkError:localException];
877 if ( [df boolForKey:@"showAlbum"] ) {
879 album = [[self currentRemote] currentSongAlbum];
881 [self networkError:localException];
885 if ( [df boolForKey:@"showArtist"] ) {
887 artist = [[self currentRemote] currentSongArtist];
889 [self networkError:localException];
893 if ( [df boolForKey:@"showComposer"] ) {
895 composer = [[self currentRemote] currentSongComposer];
897 [self networkError:localException];
901 if ( [df boolForKey:@"showTime"] ) {
903 time = [NSString stringWithFormat:@"%@: %@ / %@",
904 NSLocalizedString(@"time", @"Time"),
905 [[self currentRemote] currentSongElapsed],
906 [[self currentRemote] currentSongLength]];
908 [self networkError:localException];
912 if ( [df boolForKey:@"showTrackNumber"] ) {
917 trackNo = [[self currentRemote] currentSongTrack];
918 trackCount = [[self currentRemote] currentAlbumTrackCount];
920 [self networkError:localException];
923 if ( (trackNo > 0) || (trackCount > 0) ) {
924 track = [NSString stringWithFormat:@"%@: %i %@ %i",
925 @"Track", trackNo, @"of", trackCount];
929 if ( [df boolForKey:@"showTrackRating"] ) {
930 float currentRating = 0;
933 currentRating = [[self currentRemote] currentSongRating];
935 [self networkError:localException];
938 if (currentRating >= 0.0) {
939 rating = ( currentRating * 5 );
943 if ( [df boolForKey:@"showPlayCount"] && ![self radioIsPlaying] && [[self currentRemote] currentSource] == ITMTRemoteLibrarySource ) {
945 playCount = [[self currentRemote] currentSongPlayCount];
947 [self networkError:localException];
951 title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
953 ITDebugLog(@"Showing current track info status window.");
954 [statusWindowController showSongInfoWindowWithSource:source
966 - (void)showUpcomingSongs
970 numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
972 [self networkError:localException];
975 ITDebugLog(@"Showing upcoming songs status window.");
978 int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
979 NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
980 int curTrack = [[self currentRemote] currentSongIndex];
983 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
985 [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
989 if ([songList count] == 0) {
990 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
993 [statusWindowController showUpcomingSongsWindowWithTitles:songList];
995 [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
998 [self networkError:localException];
1007 NSMenu *menu = [statusItem menu];
1008 [(NSCarbonMenuImpl *)[menu _menuImpl] popUpMenu:menu atLocation:[NSEvent mouseLocation] width:1 forView:nil withSelectedItem:-30 withFont:[NSFont menuFontOfSize:32]];
1013 - (void)incrementVolume
1016 float volume = [[self currentRemote] volume];
1017 float dispVol = volume;
1018 ITDebugLog(@"Incrementing volume.");
1027 ITDebugLog(@"Setting volume to %f", volume);
1028 [[self currentRemote] setVolume:volume];
1030 // Show volume status window
1031 [statusWindowController showVolumeWindowWithLevel:dispVol];
1033 [self networkError:localException];
1037 - (void)decrementVolume
1040 float volume = [[self currentRemote] volume];
1041 float dispVol = volume;
1042 ITDebugLog(@"Decrementing volume.");
1051 ITDebugLog(@"Setting volume to %f", volume);
1052 [[self currentRemote] setVolume:volume];
1054 //Show volume status window
1055 [statusWindowController showVolumeWindowWithLevel:dispVol];
1057 [self networkError:localException];
1061 - (void)incrementRating
1064 float rating = [[self currentRemote] currentSongRating];
1065 ITDebugLog(@"Incrementing rating.");
1067 if ([[self currentRemote] currentPlaylistIndex] == 0) {
1068 ITDebugLog(@"No song playing, rating change aborted.");
1076 ITDebugLog(@"Setting rating to %f", rating);
1077 [[self currentRemote] setCurrentSongRating:rating];
1079 //Show rating status window
1080 [statusWindowController showRatingWindowWithRating:rating];
1082 [self networkError:localException];
1086 - (void)decrementRating
1089 float rating = [[self currentRemote] currentSongRating];
1090 ITDebugLog(@"Decrementing rating.");
1092 if ([[self currentRemote] currentPlaylistIndex] == 0) {
1093 ITDebugLog(@"No song playing, rating change aborted.");
1101 ITDebugLog(@"Setting rating to %f", rating);
1102 [[self currentRemote] setCurrentSongRating:rating];
1104 //Show rating status window
1105 [statusWindowController showRatingWindowWithRating:rating];
1107 [self networkError:localException];
1111 - (void)setRating:(ITHotKey *)sender
1113 int stars = [[sender name] characterAtIndex:9] - 48;
1114 [self selectSongRating:stars * 20];
1115 [statusWindowController showRatingWindowWithRating:(float)stars / 5.0];
1121 ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
1122 ITDebugLog(@"Toggling repeat mode.");
1123 switch (repeatMode) {
1124 case ITMTRemotePlayerRepeatOff:
1125 repeatMode = ITMTRemotePlayerRepeatAll;
1127 case ITMTRemotePlayerRepeatAll:
1128 repeatMode = ITMTRemotePlayerRepeatOne;
1130 case ITMTRemotePlayerRepeatOne:
1131 repeatMode = ITMTRemotePlayerRepeatOff;
1134 ITDebugLog(@"Setting repeat mode to %i", repeatMode);
1135 [[self currentRemote] setRepeatMode:repeatMode];
1137 //Show loop status window
1138 [statusWindowController showRepeatWindowWithMode:repeatMode];
1140 [self networkError:localException];
1144 - (void)toggleShuffle
1147 BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
1148 ITDebugLog(@"Toggling shuffle mode.");
1149 [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
1150 //Show shuffle status window
1151 ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
1152 [statusWindowController showShuffleWindow:newShuffleEnabled];
1154 [self networkError:localException];
1158 - (void)registerNowOK
1160 [[StatusWindow sharedWindow] setLocked:NO];
1161 [[StatusWindow sharedWindow] vanish:self];
1162 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1167 - (void)registerNowCancel
1169 [[StatusWindow sharedWindow] setLocked:NO];
1170 [[StatusWindow sharedWindow] vanish:self];
1171 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1173 [NSApp terminate:self];
1176 /*************************************************************************/
1178 #pragma mark NETWORK HANDLERS
1179 /*************************************************************************/
1181 - (void)setServerStatus:(BOOL)newStatus
1185 [networkController setServerStatus:YES];
1188 [networkController setServerStatus:NO];
1192 - (int)connectToServer
1195 ITDebugLog(@"Attempting to connect to shared remote.");
1196 result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
1199 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1200 currentRemote = [[[networkController networkObject] remote] retain];
1202 [self setupHotKeys];
1203 //playerRunningState = ITMTRemotePlayerRunning;
1204 playerRunningState = [[self currentRemote] playerRunningState];
1206 [refreshTimer invalidate];
1207 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1209 selector:@selector(timerUpdate)
1211 repeats:YES] retain];
1213 ITDebugLog(@"Connection successful.");
1215 } else if (result == 0) {
1216 ITDebugLog(@"Connection failed.");
1217 currentRemote = [remoteArray objectAtIndex:0];
1220 //Do something about the password being invalid
1221 ITDebugLog(@"Connection failed.");
1222 currentRemote = [remoteArray objectAtIndex:0];
1227 - (BOOL)disconnectFromServer
1229 ITDebugLog(@"Disconnecting from shared remote.");
1231 [currentRemote release];
1232 currentRemote = [remoteArray objectAtIndex:0];
1233 [networkController disconnect];
1235 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
1236 [self applicationLaunched:nil];
1238 [self applicationTerminated:nil];
1244 - (void)checkForRemoteServer
1246 [self checkForRemoteServerAndConnectImmediately:NO];
1249 - (void)checkForRemoteServerAndConnectImmediately:(BOOL)connectImmediately
1251 ITDebugLog(@"Checking for remote server.");
1252 if (!_checkingForServer) {
1253 if (!_serverCheckLock) {
1254 _serverCheckLock = [[NSLock alloc] init];
1256 [_serverCheckLock lock];
1257 _checkingForServer = YES;
1258 [_serverCheckLock unlock];
1259 [NSThread detachNewThreadSelector:@selector(runRemoteServerCheck:) toTarget:self withObject:[NSNumber numberWithBool:connectImmediately]];
1263 - (void)runRemoteServerCheck:(id)sender
1265 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1266 ITDebugLog(@"Remote server check running.");
1267 if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1268 ITDebugLog(@"Remote server found.");
1269 if ([sender boolValue]) {
1270 [self performSelectorOnMainThread:@selector(connectToServer) withObject:nil waitUntilDone:NO];
1272 [self performSelectorOnMainThread:@selector(remoteServerFound:) withObject:nil waitUntilDone:NO];
1275 ITDebugLog(@"Remote server not found.");
1276 [self performSelectorOnMainThread:@selector(remoteServerNotFound:) withObject:nil waitUntilDone:NO];
1278 [_serverCheckLock lock];
1279 _checkingForServer = NO;
1280 [_serverCheckLock unlock];
1284 - (void)remoteServerFound:(id)sender
1286 if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1287 [[StatusWindowController sharedController] showReconnectQueryWindow];
1291 - (void)remoteServerNotFound:(id)sender
1293 if (![[NetworkController sharedController] isConnectedToServer]) {
1294 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1298 - (void)networkError:(NSException *)exception
1300 ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1301 if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1302 //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);
1303 [[StatusWindowController sharedController] showNetworkErrorQueryWindow];
1304 if ([self disconnectFromServer]) {
1305 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1306 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1308 ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1315 /*if ([self connectToServer] == 0) {
1316 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1318 [self checkForRemoteServerAndConnectImmediately:YES];
1319 [[StatusWindow sharedWindow] setLocked:NO];
1320 [[StatusWindow sharedWindow] vanish:self];
1321 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1324 - (void)cancelReconnect
1326 [[StatusWindow sharedWindow] setLocked:NO];
1327 [[StatusWindow sharedWindow] vanish:self];
1328 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1331 /*************************************************************************/
1333 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1334 /*************************************************************************/
1336 - (void)applicationLaunched:(NSNotification *)note
1339 if (!note || ([[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer])) {
1340 ITDebugLog(@"Remote application launched.");
1341 playerRunningState = ITMTRemotePlayerRunning;
1342 [[self currentRemote] begin];
1343 [self setLatestSongIdentifier:@""];
1345 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1347 selector:@selector(timerUpdate)
1349 repeats:YES] retain];
1350 //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1351 [self setupHotKeys];
1354 [self networkError:localException];
1358 - (void)applicationTerminated:(NSNotification *)note
1361 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer]) {
1362 ITDebugLog(@"Remote application terminated.");
1363 playerRunningState = ITMTRemotePlayerNotRunning;
1364 [[self currentRemote] halt];
1365 [refreshTimer invalidate];
1366 [refreshTimer release];
1368 [self clearHotKeys];
1370 if ([df objectForKey:@"ShowPlayer"] != nil) {
1372 ITDebugLog(@"Setting up show player hot key.");
1373 hotKey = [[ITHotKey alloc] init];
1374 [hotKey setName:@"ShowPlayer"];
1375 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1376 [hotKey setTarget:self];
1377 [hotKey setAction:@selector(showPlayer)];
1378 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1382 [self networkError:localException];
1387 /*************************************************************************/
1389 #pragma mark NSApplication DELEGATE METHODS
1390 /*************************************************************************/
1392 - (void)applicationWillTerminate:(NSNotification *)note
1394 [networkController stopRemoteServerSearch];
1395 [self clearHotKeys];
1396 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1400 /*************************************************************************/
1402 #pragma mark DEALLOCATION METHOD
1403 /*************************************************************************/
1407 [self applicationTerminated:nil];
1409 [statusItem release];
1410 [statusWindowController release];
1411 [menuController release];
1412 [networkController release];
1413 [_serverCheckLock release];