1 #import "MainController.h"
2 #import "MenuController.h"
3 #import "PreferencesController.h"
4 #import "NetworkController.h"
5 #import "NetworkObject.h"
6 #import <ITKit/ITHotKeyCenter.h>
7 #import <ITKit/ITHotKey.h>
8 #import <ITKit/ITKeyCombo.h>
9 #import "StatusWindow.h"
10 #import "StatusWindowController.h"
11 #import "StatusItemHack.h"
13 @interface NSImage (WeeAdditions)
14 - (NSImage *)imageScaledSmoothlyToSize:(NSSize)scaledSize;
17 @implementation NSImage (WeeAdditions)
19 - (NSImage *)imageScaledSmoothlyToSize:(NSSize)scaledSize
22 NSImageRep *rep = [self bestRepresentationForDevice:nil];
24 newImage = [[NSImage alloc] initWithSize:scaledSize];
27 [[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
28 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
29 [rep drawInRect:NSMakeRect(3, 3, scaledSize.width - 6, scaledSize.height - 6)];
31 [newImage unlockFocus];
32 return [newImage autorelease];
37 @interface MainController(Private)
38 - (ITMTRemote *)loadRemote;
39 - (void)setLatestSongIdentifier:(NSString *)newIdentifier;
40 - (void)applicationLaunched:(NSNotification *)note;
41 - (void)applicationTerminated:(NSNotification *)note;
44 static MainController *sharedController;
46 @implementation MainController
48 + (MainController *)sharedController
50 return sharedController;
53 /*************************************************************************/
55 #pragma mark INITIALIZATION/DEALLOCATION METHODS
56 /*************************************************************************/
60 if ( ( self = [super init] ) ) {
61 sharedController = self;
63 remoteArray = [[NSMutableArray alloc] initWithCapacity:1];
64 [[PreferencesController sharedPrefs] setController:self];
65 statusWindowController = [StatusWindowController sharedController];
66 menuController = [[MenuController alloc] init];
67 df = [[NSUserDefaults standardUserDefaults] retain];
74 - (void)applicationDidFinishLaunching:(NSNotification *)note
76 //Turn on debug mode if needed
77 if ([df boolForKey:@"ITDebugMode"]) {
81 if (([df integerForKey:@"appVersion"] < 1200) && ([df integerForKey:@"SongsInAdvance"] > 0)) {
82 [df removePersistentDomainForName:@"com.ithinksw.menutunes"];
84 [[PreferencesController sharedPrefs] registerDefaults];
85 [[StatusWindowController sharedController] showPreferencesUpdateWindow];
88 currentRemote = [self loadRemote];
89 [[self currentRemote] begin];
91 //Turn on network stuff if needed
92 networkController = [[NetworkController alloc] init];
93 if ([df boolForKey:@"enableSharing"]) {
94 [self setServerStatus:YES];
95 } else if ([df boolForKey:@"useSharedPlayer"]) {
96 if ([self connectToServer] == 0) {
97 [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
101 //Setup for notification of the remote player launching or quitting
102 [[[NSWorkspace sharedWorkspace] notificationCenter]
104 selector:@selector(applicationTerminated:)
105 name:NSWorkspaceDidTerminateApplicationNotification
108 [[[NSWorkspace sharedWorkspace] notificationCenter]
110 selector:@selector(applicationLaunched:)
111 name:NSWorkspaceDidLaunchApplicationNotification
114 if ( ! [df objectForKey:@"menu"] ) { // If this is nil, defaults have never been registered.
115 [[PreferencesController sharedPrefs] registerDefaults];
118 if ([df boolForKey:@"ITMTNoStatusItem"]) {
121 [StatusItemHack install];
122 statusItem = [[ITStatusItem alloc]
123 initWithStatusBar:[NSStatusBar systemStatusBar]
124 withLength:NSSquareStatusItemLength];
127 bling = [[MTBlingController alloc] init];
129 registerTimer = [[NSTimer scheduledTimerWithTimeInterval:10.0
131 selector:@selector(blingTime)
133 repeats:YES] retain];
136 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
137 [self applicationLaunched:nil];
139 if ([df boolForKey:@"LaunchPlayerWithMT"])
142 [self applicationTerminated:nil];
145 [self networkError:localException];
148 [statusItem setImage:[NSImage imageNamed:@"MenuNormal"]];
149 [statusItem setAlternateImage:[NSImage imageNamed:@"MenuInverted"]];
151 [networkController startRemoteServerSearch];
155 - (ITMTRemote *)loadRemote
157 NSString *folderPath = [[NSBundle mainBundle] builtInPlugInsPath];
158 ITDebugLog(@"Gathering remotes.");
160 NSArray *bundlePathList = [NSBundle pathsForResourcesOfType:@"remote" inDirectory:folderPath];
161 NSEnumerator *enumerator = [bundlePathList objectEnumerator];
162 NSString *bundlePath;
164 while ( (bundlePath = [enumerator nextObject]) ) {
165 NSBundle* remoteBundle = [NSBundle bundleWithPath:bundlePath];
168 Class remoteClass = [remoteBundle principalClass];
170 if ([remoteClass conformsToProtocol:@protocol(ITMTRemote)] &&
171 [remoteClass isKindOfClass:[NSObject class]]) {
172 id remote = [remoteClass remote];
173 ITDebugLog(@"Adding remote at path %@", bundlePath);
174 [remoteArray addObject:remote];
179 // if ( [remoteArray count] > 0 ) { // UNCOMMENT WHEN WE HAVE > 1 PLUGIN
180 // if ( [remoteArray count] > 1 ) {
181 // [remoteArray sortUsingSelector:@selector(sortAlpha:)];
183 // [self loadModuleAccessUI]; //Comment out this line to disable remote visibility
186 // NSLog(@"%@", [remoteArray objectAtIndex:0]); //DEBUG
187 return [remoteArray objectAtIndex:0];
190 /*************************************************************************/
192 #pragma mark INSTANCE METHODS
193 /*************************************************************************/
195 /*- (void)startTimerInNewThread
197 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
198 NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
199 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:0.5
201 selector:@selector(timerUpdate)
203 repeats:YES] retain];
205 ITDebugLog(@"Timer started.");
209 - (void)setBlingTime:(NSDate*)date
211 NSMutableDictionary *globalPrefs;
213 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
215 [globalPrefs setObject:date forKey:@"ITMTTrialStart"];
216 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
218 [globalPrefs removeObjectForKey:@"ITMTTrialStart"];
219 [globalPrefs removeObjectForKey:@"ITMTTrialVers"];
221 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
223 [globalPrefs release];
226 - (NSDate*)getBlingTime
229 return [[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialStart"];
234 NSDate *now = [NSDate date];
235 if (![self blingBling]) {
236 if ( (! [self getBlingTime] ) || ([now timeIntervalSinceDate:[self getBlingTime]] < 0) ) {
237 [self setBlingTime:now];
238 } else if ([[[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialVers"] intValue] < MT_CURRENT_VERSION) {
239 if ([now timeIntervalSinceDate:[self getBlingTime]] >= 345600) {
240 [self setBlingTime:[now addTimeInterval:-259200]];
242 NSMutableDictionary *globalPrefs;
244 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
245 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
246 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
248 [globalPrefs release];
252 if ( ([now timeIntervalSinceDate:[self getBlingTime]] >= 604800) && (blinged != YES) ) {
254 [statusItem setEnabled:NO];
256 if ([refreshTimer isValid]) {
257 [refreshTimer invalidate];
259 [statusWindowController showRegistrationQueryWindow];
263 [statusItem setEnabled:YES];
265 if (![refreshTimer isValid]) {
266 [refreshTimer release];
267 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:0.5
269 selector:@selector(timerUpdate)
271 repeats:YES] retain];
275 [self setBlingTime:nil];
286 if ( ! ([bling checkDone] == 2475) ) {
293 - (BOOL)songIsPlaying
295 NSString *identifier = nil;
297 identifier = [[self currentRemote] playerStateUniqueIdentifier];
299 [self networkError:localException];
301 return ( ! ([identifier isEqualToString:@"0-0"]) );
304 - (BOOL)radioIsPlaying
306 ITMTRemotePlayerPlaylistClass class = nil;
308 class = [[self currentRemote] currentPlaylistClass];
310 [self networkError:localException];
312 return (class == ITMTRemotePlayerRadioPlaylist );
317 NSString *identifier = nil;
319 identifier = [[self currentRemote] playerStateUniqueIdentifier];
321 [self networkError:localException];
323 return ( ! [identifier isEqualToString:_latestSongIdentifier] );
326 - (NSString *)latestSongIdentifier
328 return _latestSongIdentifier;
331 - (void)setLatestSongIdentifier:(NSString *)newIdentifier
333 ITDebugLog(@"Setting latest song identifier to %@", newIdentifier);
334 [_latestSongIdentifier autorelease];
335 _latestSongIdentifier = [newIdentifier copy];
340 if ([networkController isConnectedToServer]) {
341 [statusItem setMenu:[menuController menu]];
344 if ( [self songChanged] && (timerUpdating != YES) && (playerRunningState == ITMTRemotePlayerRunning) ) {
345 ITDebugLog(@"The song changed.");
347 if ([df boolForKey:@"runScripts"]) {
348 NSArray *scripts = [[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"]];
349 NSEnumerator *scriptsEnum = [scripts objectEnumerator];
350 NSString *nextScript;
351 ITDebugLog(@"Running AppleScripts for song change.");
352 while ( (nextScript = [scriptsEnum nextObject]) ) {
354 NSAppleScript *currentScript = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"] stringByAppendingPathComponent:nextScript]] error:&error];
355 NSLog(@"Running script: %@", nextScript);
356 if (!currentScript || ![currentScript executeAndReturnError:nil]) {
357 ITDebugLog(@"Error running script %@.", nextScript);
359 [currentScript release];
366 latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
367 [menuController rebuildSubmenus];
369 if ( [df boolForKey:@"showSongInfoOnChange"] ) {
370 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
373 [self setLatestSongIdentifier:[[self currentRemote] playerStateUniqueIdentifier]];
375 NSString *artist = [[self currentRemote] currentSongArtist];
376 NSString *title = [[self currentRemote] currentSongTitle];
379 toolTip = [NSString stringWithFormat:@"%@ - %@", artist, title];
383 toolTip = @"No Song Playing";
385 [statusItem setToolTip:toolTip];
387 [self networkError:localException];
396 ITDebugLog(@"Menu clicked.");
397 if ([networkController isConnectedToServer]) {
398 //Used the cached version
403 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
404 [statusItem setMenu:[menuController menu]];
406 [statusItem setMenu:[menuController menuForNoPlayer]];
409 [self networkError:localException];
422 ITMTRemotePlayerPlayingState state = [[self currentRemote] playerPlayingState];
423 ITDebugLog(@"Play/Pause toggled");
424 if (state == ITMTRemotePlayerPlaying) {
425 [[self currentRemote] pause];
426 } else if ((state == ITMTRemotePlayerForwarding) || (state == ITMTRemotePlayerRewinding)) {
427 [[self currentRemote] pause];
428 [[self currentRemote] play];
430 [[self currentRemote] play];
433 [self networkError:localException];
441 ITDebugLog(@"Going to next song.");
443 [[self currentRemote] goToNextSong];
445 [self networkError:localException];
452 ITDebugLog(@"Going to previous song.");
454 [[self currentRemote] goToPreviousSong];
456 [self networkError:localException];
463 ITDebugLog(@"Fast forwarding.");
465 [[self currentRemote] forward];
467 [self networkError:localException];
474 ITDebugLog(@"Rewinding.");
476 [[self currentRemote] rewind];
478 [self networkError:localException];
483 - (void)selectPlaylistAtIndex:(int)index
485 ITDebugLog(@"Selecting playlist %i", index);
487 [[self currentRemote] switchToPlaylistAtIndex:(index % 1000) ofSourceAtIndex:(index / 1000)];
488 //[[self currentRemote] switchToPlaylistAtIndex:index];
490 [self networkError:localException];
495 - (void)selectSongAtIndex:(int)index
497 ITDebugLog(@"Selecting song %i", index);
499 [[self currentRemote] switchToSongAtIndex:index];
501 [self networkError:localException];
506 - (void)selectSongRating:(int)rating
508 ITDebugLog(@"Selecting song rating %i", rating);
510 [[self currentRemote] setCurrentSongRating:(float)rating / 100.0];
512 [self networkError:localException];
517 - (void)selectEQPresetAtIndex:(int)index
519 ITDebugLog(@"Selecting EQ preset %i", index);
521 [[self currentRemote] switchToEQAtIndex:index];
523 [self networkError:localException];
530 ITDebugLog(@"Beginning show player.");
531 if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
532 ITDebugLog(@"Showing player interface.");
534 [[self currentRemote] showPrimaryInterface];
536 [self networkError:localException];
539 ITDebugLog(@"Launching player.");
542 if ( (path = [df stringForKey:@"CustomPlayerPath"]) ) {
544 path = [[self currentRemote] playerFullName];
546 if (![[NSWorkspace sharedWorkspace] launchApplication:path]) {
547 ITDebugLog(@"Error Launching Player");
550 [self networkError:localException];
553 ITDebugLog(@"Finished show player.");
556 - (void)showPreferences
558 ITDebugLog(@"Show preferences.");
559 [[PreferencesController sharedPrefs] showPrefsWindow:self];
562 - (void)showPreferencesAndClose
564 ITDebugLog(@"Show preferences.");
565 [[PreferencesController sharedPrefs] showPrefsWindow:self];
566 [[StatusWindow sharedWindow] setLocked:NO];
567 [[StatusWindow sharedWindow] vanish:self];
568 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
571 - (void)showTestWindow
573 [self showCurrentTrackInfo];
576 - (void)quitMenuTunes
578 ITDebugLog(@"Quitting MenuTunes.");
579 [NSApp terminate:self];
585 - (void)closePreferences
587 ITDebugLog(@"Preferences closed.");
588 if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
593 - (ITMTRemote *)currentRemote
595 if ([networkController isConnectedToServer] && ![[networkController networkObject] isValid]) {
596 [self networkError:nil];
599 return currentRemote;
610 NSEnumerator *hotKeyEnumerator = [[[ITHotKeyCenter sharedCenter] allHotKeys] objectEnumerator];
611 ITHotKey *nextHotKey;
612 ITDebugLog(@"Clearing hot keys.");
613 while ( (nextHotKey = [hotKeyEnumerator nextObject]) ) {
614 [[ITHotKeyCenter sharedCenter] unregisterHotKey:nextHotKey];
616 ITDebugLog(@"Done clearing hot keys.");
622 ITDebugLog(@"Setting up hot keys.");
624 if (playerRunningState == ITMTRemotePlayerNotRunning) {
628 if ([df objectForKey:@"PlayPause"] != nil) {
629 ITDebugLog(@"Setting up play pause hot key.");
630 hotKey = [[ITHotKey alloc] init];
631 [hotKey setName:@"PlayPause"];
632 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PlayPause"]]];
633 [hotKey setTarget:self];
634 [hotKey setAction:@selector(playPause)];
635 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
638 if ([df objectForKey:@"NextTrack"] != nil) {
639 ITDebugLog(@"Setting up next track hot key.");
640 hotKey = [[ITHotKey alloc] init];
641 [hotKey setName:@"NextTrack"];
642 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"NextTrack"]]];
643 [hotKey setTarget:self];
644 [hotKey setAction:@selector(nextSong)];
645 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
648 if ([df objectForKey:@"PrevTrack"] != nil) {
649 ITDebugLog(@"Setting up previous track hot key.");
650 hotKey = [[ITHotKey alloc] init];
651 [hotKey setName:@"PrevTrack"];
652 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PrevTrack"]]];
653 [hotKey setTarget:self];
654 [hotKey setAction:@selector(prevSong)];
655 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
658 if ([df objectForKey:@"ShowPlayer"] != nil) {
659 ITDebugLog(@"Setting up show player hot key.");
660 hotKey = [[ITHotKey alloc] init];
661 [hotKey setName:@"ShowPlayer"];
662 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
663 [hotKey setTarget:self];
664 [hotKey setAction:@selector(showPlayer)];
665 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
668 if ([df objectForKey:@"TrackInfo"] != nil) {
669 ITDebugLog(@"Setting up track info hot key.");
670 hotKey = [[ITHotKey alloc] init];
671 [hotKey setName:@"TrackInfo"];
672 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"TrackInfo"]]];
673 [hotKey setTarget:self];
674 [hotKey setAction:@selector(showCurrentTrackInfo)];
675 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
678 if ([df objectForKey:@"UpcomingSongs"] != nil) {
679 ITDebugLog(@"Setting up upcoming songs hot key.");
680 hotKey = [[ITHotKey alloc] init];
681 [hotKey setName:@"UpcomingSongs"];
682 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"UpcomingSongs"]]];
683 [hotKey setTarget:self];
684 [hotKey setAction:@selector(showUpcomingSongs)];
685 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
688 if ([df objectForKey:@"ToggleLoop"] != nil) {
689 ITDebugLog(@"Setting up toggle loop hot key.");
690 hotKey = [[ITHotKey alloc] init];
691 [hotKey setName:@"ToggleLoop"];
692 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleLoop"]]];
693 [hotKey setTarget:self];
694 [hotKey setAction:@selector(toggleLoop)];
695 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
698 if ([df objectForKey:@"ToggleShuffle"] != nil) {
699 ITDebugLog(@"Setting up toggle shuffle hot key.");
700 hotKey = [[ITHotKey alloc] init];
701 [hotKey setName:@"ToggleShuffle"];
702 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShuffle"]]];
703 [hotKey setTarget:self];
704 [hotKey setAction:@selector(toggleShuffle)];
705 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
708 if ([df objectForKey:@"IncrementVolume"] != nil) {
709 ITDebugLog(@"Setting up increment volume hot key.");
710 hotKey = [[ITHotKey alloc] init];
711 [hotKey setName:@"IncrementVolume"];
712 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementVolume"]]];
713 [hotKey setTarget:self];
714 [hotKey setAction:@selector(incrementVolume)];
715 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
718 if ([df objectForKey:@"DecrementVolume"] != nil) {
719 ITDebugLog(@"Setting up decrement volume hot key.");
720 hotKey = [[ITHotKey alloc] init];
721 [hotKey setName:@"DecrementVolume"];
722 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementVolume"]]];
723 [hotKey setTarget:self];
724 [hotKey setAction:@selector(decrementVolume)];
725 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
728 if ([df objectForKey:@"IncrementRating"] != nil) {
729 ITDebugLog(@"Setting up increment rating hot key.");
730 hotKey = [[ITHotKey alloc] init];
731 [hotKey setName:@"IncrementRating"];
732 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementRating"]]];
733 [hotKey setTarget:self];
734 [hotKey setAction:@selector(incrementRating)];
735 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
738 if ([df objectForKey:@"DecrementRating"] != nil) {
739 ITDebugLog(@"Setting up decrement rating hot key.");
740 hotKey = [[ITHotKey alloc] init];
741 [hotKey setName:@"DecrementRating"];
742 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementRating"]]];
743 [hotKey setTarget:self];
744 [hotKey setAction:@selector(decrementRating)];
745 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
747 ITDebugLog(@"Finished setting up hot keys.");
750 - (void)showCurrentTrackInfo
752 ITMTRemotePlayerSource source = 0;
753 NSString *title = nil;
754 NSString *album = nil;
755 NSString *artist = nil;
756 NSString *time = nil;
757 NSString *track = nil;
762 source = [[self currentRemote] currentSource];
763 title = [[self currentRemote] currentSongTitle];
765 [self networkError:localException];
768 ITDebugLog(@"Showing track info status window.");
772 if ( [df boolForKey:@"showAlbum"] ) {
774 album = [[self currentRemote] currentSongAlbum];
776 [self networkError:localException];
780 if ( [df boolForKey:@"showArtist"] ) {
782 artist = [[self currentRemote] currentSongArtist];
784 [self networkError:localException];
788 if ( [df boolForKey:@"showTime"] ) {
790 time = [NSString stringWithFormat:@"%@: %@ / %@",
792 [[self currentRemote] currentSongElapsed],
793 [[self currentRemote] currentSongLength]];
795 [self networkError:localException];
799 if ( [df boolForKey:@"showTrackNumber"] ) {
804 trackNo = [[self currentRemote] currentSongTrack];
805 trackCount = [[self currentRemote] currentAlbumTrackCount];
807 [self networkError:localException];
810 if ( (trackNo > 0) || (trackCount > 0) ) {
811 track = [NSString stringWithFormat:@"%@: %i %@ %i",
812 @"Track", trackNo, @"of", trackCount];
816 if ( [df boolForKey:@"showTrackRating"] ) {
817 float currentRating = 0;
820 currentRating = [[self currentRemote] currentSongRating];
822 [self networkError:localException];
825 if (currentRating >= 0.0) {
826 rating = ( currentRating * 5 );
830 if ( [df boolForKey:@"showAlbumArtwork"] ) {
831 NSSize oldSize, newSize;
833 art = [[self currentRemote] currentSongAlbumArt];
834 oldSize = [art size];
835 if (oldSize.width > oldSize.height) newSize = NSMakeSize(110,oldSize.height * (110.0f / oldSize.width));
836 else newSize = NSMakeSize(oldSize.width * (110.0f / oldSize.height),110);
837 art = [[[[NSImage alloc] initWithData:[art TIFFRepresentation]] autorelease] imageScaledSmoothlyToSize:newSize];
839 [self networkError:localException];
844 title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
846 [statusWindowController showSongInfoWindowWithSource:source
856 - (void)showUpcomingSongs
860 numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
862 [self networkError:localException];
865 ITDebugLog(@"Showing upcoming songs status window.");
868 int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
869 NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
870 int curTrack = [[self currentRemote] currentSongIndex];
873 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
875 [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
879 if ([songList count] == 0) {
880 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
883 [statusWindowController showUpcomingSongsWindowWithTitles:songList];
885 [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
888 [self networkError:localException];
892 - (void)incrementVolume
895 float volume = [[self currentRemote] volume];
896 float dispVol = volume;
897 ITDebugLog(@"Incrementing volume.");
906 ITDebugLog(@"Setting volume to %f", volume);
907 [[self currentRemote] setVolume:volume];
909 // Show volume status window
910 [statusWindowController showVolumeWindowWithLevel:dispVol];
912 [self networkError:localException];
916 - (void)decrementVolume
919 float volume = [[self currentRemote] volume];
920 float dispVol = volume;
921 ITDebugLog(@"Decrementing volume.");
930 ITDebugLog(@"Setting volume to %f", volume);
931 [[self currentRemote] setVolume:volume];
933 //Show volume status window
934 [statusWindowController showVolumeWindowWithLevel:dispVol];
936 [self networkError:localException];
940 - (void)incrementRating
943 float rating = [[self currentRemote] currentSongRating];
944 ITDebugLog(@"Incrementing rating.");
946 if ([[self currentRemote] currentPlaylistIndex] == 0) {
947 ITDebugLog(@"No song playing, rating change aborted.");
955 ITDebugLog(@"Setting rating to %f", rating);
956 [[self currentRemote] setCurrentSongRating:rating];
958 //Show rating status window
959 [statusWindowController showRatingWindowWithRating:rating];
961 [self networkError:localException];
965 - (void)decrementRating
968 float rating = [[self currentRemote] currentSongRating];
969 ITDebugLog(@"Decrementing rating.");
971 if ([[self currentRemote] currentPlaylistIndex] == 0) {
972 ITDebugLog(@"No song playing, rating change aborted.");
980 ITDebugLog(@"Setting rating to %f", rating);
981 [[self currentRemote] setCurrentSongRating:rating];
983 //Show rating status window
984 [statusWindowController showRatingWindowWithRating:rating];
986 [self networkError:localException];
993 ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
994 ITDebugLog(@"Toggling repeat mode.");
995 switch (repeatMode) {
996 case ITMTRemotePlayerRepeatOff:
997 repeatMode = ITMTRemotePlayerRepeatAll;
999 case ITMTRemotePlayerRepeatAll:
1000 repeatMode = ITMTRemotePlayerRepeatOne;
1002 case ITMTRemotePlayerRepeatOne:
1003 repeatMode = ITMTRemotePlayerRepeatOff;
1006 ITDebugLog(@"Setting repeat mode to %i", repeatMode);
1007 [[self currentRemote] setRepeatMode:repeatMode];
1009 //Show loop status window
1010 [statusWindowController showRepeatWindowWithMode:repeatMode];
1012 [self networkError:localException];
1016 - (void)toggleShuffle
1019 BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
1020 ITDebugLog(@"Toggling shuffle mode.");
1021 [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
1022 //Show shuffle status window
1023 ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
1024 [statusWindowController showShuffleWindow:newShuffleEnabled];
1026 [self networkError:localException];
1030 - (void)registerNowOK
1032 [[StatusWindow sharedWindow] setLocked:NO];
1033 [[StatusWindow sharedWindow] vanish:self];
1034 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1039 - (void)registerNowCancel
1041 [[StatusWindow sharedWindow] setLocked:NO];
1042 [[StatusWindow sharedWindow] vanish:self];
1043 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1045 [NSApp terminate:self];
1048 /*************************************************************************/
1050 #pragma mark NETWORK HANDLERS
1051 /*************************************************************************/
1053 - (void)setServerStatus:(BOOL)newStatus
1057 [networkController setServerStatus:YES];
1060 [networkController setServerStatus:NO];
1064 - (int)connectToServer
1067 ITDebugLog(@"Attempting to connect to shared remote.");
1068 result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
1071 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1072 currentRemote = [[[networkController networkObject] remote] retain];
1073 [refreshTimer invalidate];
1074 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1076 selector:@selector(timerUpdate)
1078 repeats:YES] retain];
1080 ITDebugLog(@"Connection successful.");
1082 } else if (result == 0) {
1083 ITDebugLog(@"Connection failed.");
1084 currentRemote = [remoteArray objectAtIndex:0];
1087 //Do something about the password being invalid
1088 ITDebugLog(@"Connection failed.");
1089 currentRemote = [remoteArray objectAtIndex:0];
1094 - (BOOL)disconnectFromServer
1096 ITDebugLog(@"Disconnecting from shared remote.");
1098 [currentRemote release];
1099 currentRemote = [remoteArray objectAtIndex:0];
1100 [networkController disconnect];
1105 - (void)checkForRemoteServer:(NSTimer *)timer
1107 ITDebugLog(@"Checking for remote server.");
1108 if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1109 ITDebugLog(@"Remote server found.");
1111 if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1112 [[StatusWindowController sharedController] showReconnectQueryWindow];
1115 ITDebugLog(@"Remote server not found.");
1119 - (void)networkError:(NSException *)exception
1121 ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1122 if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1123 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);
1124 if ([self disconnectFromServer]) {
1125 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1126 [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
1128 ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1135 if ([self connectToServer] == 0) {
1136 [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
1138 [[StatusWindow sharedWindow] setLocked:NO];
1139 [[StatusWindow sharedWindow] vanish:self];
1140 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1143 - (void)cancelReconnect
1145 [[StatusWindow sharedWindow] setLocked:NO];
1146 [[StatusWindow sharedWindow] vanish:self];
1147 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1150 /*************************************************************************/
1152 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1153 /*************************************************************************/
1155 - (void)applicationLaunched:(NSNotification *)note
1158 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]]) {
1159 ITDebugLog(@"Remote application launched.");
1160 playerRunningState = ITMTRemotePlayerRunning;
1161 [[self currentRemote] begin];
1162 [self setLatestSongIdentifier:@""];
1164 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1166 selector:@selector(timerUpdate)
1168 repeats:YES] retain];
1169 //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1170 [self setupHotKeys];
1173 [self networkError:localException];
1177 - (void)applicationTerminated:(NSNotification *)note
1180 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]]) {
1181 ITDebugLog(@"Remote application terminated.");
1182 playerRunningState = ITMTRemotePlayerNotRunning;
1183 [[self currentRemote] halt];
1184 [refreshTimer invalidate];
1185 [refreshTimer release];
1187 [self clearHotKeys];
1189 if ([df objectForKey:@"ShowPlayer"] != nil) {
1191 ITDebugLog(@"Setting up show player hot key.");
1192 hotKey = [[ITHotKey alloc] init];
1193 [hotKey setName:@"ShowPlayer"];
1194 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1195 [hotKey setTarget:self];
1196 [hotKey setAction:@selector(showPlayer)];
1197 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1201 [self networkError:localException];
1206 /*************************************************************************/
1208 #pragma mark NSApplication DELEGATE METHODS
1209 /*************************************************************************/
1211 - (void)applicationWillTerminate:(NSNotification *)note
1213 [networkController stopRemoteServerSearch];
1214 [self clearHotKeys];
1215 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1219 /*************************************************************************/
1221 #pragma mark DEALLOCATION METHOD
1222 /*************************************************************************/
1226 [self applicationTerminated:nil];
1228 [statusItem release];
1229 [statusWindowController release];
1230 [menuController release];
1231 [networkController release];