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 @implementation NSImage (SmoothAdditions)
15 - (NSImage *)imageScaledSmoothlyToSize:(NSSize)scaledSize
18 NSImageRep *rep = [self bestRepresentationForDevice:nil];
20 newImage = [[NSImage alloc] initWithSize:scaledSize];
23 [[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
24 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
25 [rep drawInRect:NSMakeRect(3, 3, scaledSize.width - 6, scaledSize.height - 6)];
27 [newImage unlockFocus];
28 return [newImage autorelease];
33 @interface MainController(Private)
34 - (ITMTRemote *)loadRemote;
35 - (void)setLatestSongIdentifier:(NSString *)newIdentifier;
36 - (void)applicationLaunched:(NSNotification *)note;
37 - (void)applicationTerminated:(NSNotification *)note;
40 static MainController *sharedController;
42 @implementation MainController
44 + (MainController *)sharedController
46 return sharedController;
49 /*************************************************************************/
51 #pragma mark INITIALIZATION/DEALLOCATION METHODS
52 /*************************************************************************/
56 if ( ( self = [super init] ) ) {
57 sharedController = self;
59 remoteArray = [[NSMutableArray alloc] initWithCapacity:1];
60 [[PreferencesController sharedPrefs] setController:self];
61 statusWindowController = [StatusWindowController sharedController];
62 menuController = [[MenuController alloc] init];
63 df = [[NSUserDefaults standardUserDefaults] retain];
70 - (void)applicationDidFinishLaunching:(NSNotification *)note
72 //Turn on debug mode if needed
73 if ([df boolForKey:@"ITDebugMode"]) {
77 if (([df integerForKey:@"appVersion"] < 1200) && ([df integerForKey:@"SongsInAdvance"] > 0)) {
78 [df removePersistentDomainForName:@"com.ithinksw.menutunes"];
80 [[PreferencesController sharedPrefs] registerDefaults];
81 [[StatusWindowController sharedController] showPreferencesUpdateWindow];
84 currentRemote = [self loadRemote];
85 [[self currentRemote] begin];
87 //Turn on network stuff if needed
88 networkController = [[NetworkController alloc] init];
89 if ([df boolForKey:@"enableSharing"]) {
90 [self setServerStatus:YES];
91 } else if ([df boolForKey:@"useSharedPlayer"]) {
92 [self checkForRemoteServerAndConnectImmediately:YES];
95 //Setup for notification of the remote player launching or quitting
96 [[[NSWorkspace sharedWorkspace] notificationCenter]
98 selector:@selector(applicationTerminated:)
99 name:NSWorkspaceDidTerminateApplicationNotification
102 [[[NSWorkspace sharedWorkspace] notificationCenter]
104 selector:@selector(applicationLaunched:)
105 name:NSWorkspaceDidLaunchApplicationNotification
108 if (![df objectForKey:@"menu"]) { // If this is nil, defaults have never been registered.
109 [[PreferencesController sharedPrefs] registerDefaults];
112 if ([df boolForKey:@"ITMTNoStatusItem"]) {
115 [StatusItemHack install];
116 statusItem = [[ITStatusItem alloc]
117 initWithStatusBar:[NSStatusBar systemStatusBar]
118 withLength:NSSquareStatusItemLength];
121 bling = [[MTBlingController alloc] init];
123 registerTimer = [[NSTimer scheduledTimerWithTimeInterval:10.0
125 selector:@selector(blingTime)
127 repeats:YES] retain];
130 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
131 [self applicationLaunched:nil];
133 if ([df boolForKey:@"LaunchPlayerWithMT"])
136 [self applicationTerminated:nil];
139 [self networkError:localException];
142 [statusItem setImage:[NSImage imageNamed:@"MenuNormal"]];
143 [statusItem setAlternateImage:[NSImage imageNamed:@"MenuInverted"]];
145 [networkController startRemoteServerSearch];
149 - (ITMTRemote *)loadRemote
151 NSString *folderPath = [[NSBundle mainBundle] builtInPlugInsPath];
152 ITDebugLog(@"Gathering remotes.");
154 NSArray *bundlePathList = [NSBundle pathsForResourcesOfType:@"remote" inDirectory:folderPath];
155 NSEnumerator *enumerator = [bundlePathList objectEnumerator];
156 NSString *bundlePath;
158 while ( (bundlePath = [enumerator nextObject]) ) {
159 NSBundle* remoteBundle = [NSBundle bundleWithPath:bundlePath];
162 Class remoteClass = [remoteBundle principalClass];
164 if ([remoteClass conformsToProtocol:@protocol(ITMTRemote)] &&
165 [(NSObject *)remoteClass isKindOfClass:[NSObject class]]) {
166 id remote = [remoteClass remote];
167 ITDebugLog(@"Adding remote at path %@", bundlePath);
168 [remoteArray addObject:remote];
173 // if ( [remoteArray count] > 0 ) { // UNCOMMENT WHEN WE HAVE > 1 PLUGIN
174 // if ( [remoteArray count] > 1 ) {
175 // [remoteArray sortUsingSelector:@selector(sortAlpha:)];
177 // [self loadModuleAccessUI]; //Comment out this line to disable remote visibility
180 // NSLog(@"%@", [remoteArray objectAtIndex:0]); //DEBUG
181 return [remoteArray objectAtIndex:0];
184 /*************************************************************************/
186 #pragma mark INSTANCE METHODS
187 /*************************************************************************/
189 /*- (void)startTimerInNewThread
191 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
192 NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
193 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:0.5
195 selector:@selector(timerUpdate)
197 repeats:YES] retain];
199 ITDebugLog(@"Timer started.");
203 - (void)setBlingTime:(NSDate*)date
205 NSMutableDictionary *globalPrefs;
207 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
209 [globalPrefs setObject:date forKey:@"ITMTTrialStart"];
210 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
212 [globalPrefs removeObjectForKey:@"ITMTTrialStart"];
213 [globalPrefs removeObjectForKey:@"ITMTTrialVers"];
215 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
217 [globalPrefs release];
220 - (NSDate*)getBlingTime
223 return [[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialStart"];
228 NSDate *now = [NSDate date];
229 if (![self blingBling]) {
230 if ( (! [self getBlingTime] ) || ([now timeIntervalSinceDate:[self getBlingTime]] < 0) ) {
231 [self setBlingTime:now];
232 } else if ([[[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialVers"] intValue] < MT_CURRENT_VERSION) {
233 if ([now timeIntervalSinceDate:[self getBlingTime]] >= 345600) {
234 [self setBlingTime:[now addTimeInterval:-259200]];
236 NSMutableDictionary *globalPrefs;
238 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
239 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
240 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
242 [globalPrefs release];
246 if ( ([now timeIntervalSinceDate:[self getBlingTime]] >= 604800) && (blinged != YES) ) {
248 [statusItem setEnabled:NO];
250 if ([refreshTimer isValid]) {
251 [refreshTimer invalidate];
253 [statusWindowController showRegistrationQueryWindow];
257 [statusItem setEnabled:YES];
259 if (![refreshTimer isValid]) {
260 [refreshTimer release];
261 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
263 selector:@selector(timerUpdate)
265 repeats:YES] retain];
269 [self setBlingTime:nil];
280 if ( ! ([bling checkDone] == 2475) ) {
287 - (BOOL)songIsPlaying
289 NSString *identifier = nil;
291 identifier = [[self currentRemote] playerStateUniqueIdentifier];
293 [self networkError:localException];
295 return ( ! ([identifier isEqualToString:@"0-0"]) );
298 - (BOOL)radioIsPlaying
300 ITMTRemotePlayerPlaylistClass class = nil;
302 class = [[self currentRemote] currentPlaylistClass];
304 [self networkError:localException];
306 return (class == ITMTRemotePlayerRadioPlaylist );
311 NSString *identifier = nil;
313 identifier = [[self currentRemote] playerStateUniqueIdentifier];
315 [self networkError:localException];
317 return ( ! [identifier isEqualToString:_latestSongIdentifier] );
320 - (NSString *)latestSongIdentifier
322 return _latestSongIdentifier;
325 - (void)setLatestSongIdentifier:(NSString *)newIdentifier
327 ITDebugLog(@"Setting latest song identifier:");
328 ITDebugLog(@" - Identifier: %@", newIdentifier);
329 [_latestSongIdentifier autorelease];
330 _latestSongIdentifier = [newIdentifier retain];
335 if ( [self songChanged] && (timerUpdating != YES) && (playerRunningState == ITMTRemotePlayerRunning) ) {
336 ITDebugLog(@"The song changed.");
338 if ([df boolForKey:@"runScripts"]) {
339 NSArray *scripts = [[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"]];
340 NSEnumerator *scriptsEnum = [scripts objectEnumerator];
341 NSString *nextScript;
342 ITDebugLog(@"Running AppleScripts for song change.");
343 while ( (nextScript = [scriptsEnum nextObject]) ) {
345 NSAppleScript *currentScript = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"] stringByAppendingPathComponent:nextScript]] error:&error];
346 ITDebugLog(@"Running script: %@", nextScript);
347 if (!currentScript || ![currentScript executeAndReturnError:nil]) {
348 ITDebugLog(@"Error running script %@.", nextScript);
350 [currentScript release];
355 [statusItem setEnabled:NO];
358 latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
359 [menuController rebuildSubmenus];
361 if ( [df boolForKey:@"showSongInfoOnChange"] ) {
362 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
365 [self setLatestSongIdentifier:[[self currentRemote] playerStateUniqueIdentifier]];
367 //Create the tooltip for the status item
368 if ( [df boolForKey:@"showToolTip"] ) {
369 NSString *artist = [[self currentRemote] currentSongArtist];
370 NSString *title = [[self currentRemote] currentSongTitle];
372 ITDebugLog(@"Creating status item tooltip.");
374 toolTip = [NSString stringWithFormat:@"%@ - %@", artist, title];
378 toolTip = @"No Song Playing";
380 [statusItem setToolTip:toolTip];
382 [statusItem setToolTip:nil];
385 [self networkError:localException];
389 [statusItem setEnabled:YES];
392 if ([networkController isConnectedToServer]) {
393 [statusItem setMenu:([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) ? [menuController menu] : [menuController menuForNoPlayer]];
399 ITDebugLog(@"Menu clicked.");
400 if ([networkController isConnectedToServer]) {
401 //Used the cached version
406 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
407 [statusItem setMenu:[menuController menu]];
409 [statusItem setMenu:[menuController menuForNoPlayer]];
412 [self networkError:localException];
425 ITMTRemotePlayerPlayingState state = [[self currentRemote] playerPlayingState];
426 ITDebugLog(@"Play/Pause toggled");
427 if (state == ITMTRemotePlayerPlaying) {
428 [[self currentRemote] pause];
429 } else if ((state == ITMTRemotePlayerForwarding) || (state == ITMTRemotePlayerRewinding)) {
430 [[self currentRemote] pause];
431 [[self currentRemote] play];
433 [[self currentRemote] play];
436 [self networkError:localException];
444 ITDebugLog(@"Going to next song.");
446 [[self currentRemote] goToNextSong];
448 [self networkError:localException];
455 ITDebugLog(@"Going to previous song.");
457 [[self currentRemote] goToPreviousSong];
459 [self networkError:localException];
466 ITDebugLog(@"Fast forwarding.");
468 [[self currentRemote] forward];
470 [self networkError:localException];
477 ITDebugLog(@"Rewinding.");
479 [[self currentRemote] rewind];
481 [self networkError:localException];
486 - (void)selectPlaylistAtIndex:(int)index
488 ITDebugLog(@"Selecting playlist %i", index);
490 [[self currentRemote] switchToPlaylistAtIndex:(index % 1000) ofSourceAtIndex:(index / 1000)];
491 //[[self currentRemote] switchToPlaylistAtIndex:index];
493 [self networkError:localException];
498 - (void)selectSongAtIndex:(int)index
500 ITDebugLog(@"Selecting song %i", index);
502 [[self currentRemote] switchToSongAtIndex:index];
504 [self networkError:localException];
509 - (void)selectSongRating:(int)rating
511 ITDebugLog(@"Selecting song rating %i", rating);
513 [[self currentRemote] setCurrentSongRating:(float)rating / 100.0];
515 [self networkError:localException];
520 - (void)selectEQPresetAtIndex:(int)index
522 ITDebugLog(@"Selecting EQ preset %i", index);
524 [[self currentRemote] switchToEQAtIndex:index];
526 [self networkError:localException];
533 ITDebugLog(@"Beginning show player.");
534 //if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
535 ITDebugLog(@"Showing player interface.");
537 [[self currentRemote] showPrimaryInterface];
539 [self networkError:localException];
542 ITDebugLog(@"Launching player.");
545 if ( (path = [df stringForKey:@"CustomPlayerPath"]) ) {
547 pathITDebugLog(@"Showing player interface."); = [[self currentRemote] playerFullName];
549 if (![[NSWorkspace sharedWorkspace] launchApplication:path]) {
550 ITDebugLog(@"Error Launching Player");
553 [self networkError:localException];
556 ITDebugLog(@"Finished show player.");
559 - (void)showPreferences
561 ITDebugLog(@"Show preferences.");
562 [[PreferencesController sharedPrefs] showPrefsWindow:self];
565 - (void)showPreferencesAndClose
567 ITDebugLog(@"Show preferences.");
568 [[PreferencesController sharedPrefs] showPrefsWindow:self];
569 [[StatusWindow sharedWindow] setLocked:NO];
570 [[StatusWindow sharedWindow] vanish:self];
571 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
574 - (void)showTestWindow
576 [self showCurrentTrackInfo];
579 - (void)quitMenuTunes
581 ITDebugLog(@"Quitting MenuTunes.");
582 [NSApp terminate:self];
588 - (MenuController *)menuController
590 return menuController;
593 - (void)closePreferences
595 ITDebugLog(@"Preferences closed.");
596 if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
601 - (ITMTRemote *)currentRemote
603 if ([networkController isConnectedToServer] && ![[networkController networkObject] isValid]) {
604 [self networkError:nil];
607 return currentRemote;
618 NSEnumerator *hotKeyEnumerator = [[[ITHotKeyCenter sharedCenter] allHotKeys] objectEnumerator];
619 ITHotKey *nextHotKey;
620 ITDebugLog(@"Clearing hot keys.");
621 while ( (nextHotKey = [hotKeyEnumerator nextObject]) ) {
622 [[ITHotKeyCenter sharedCenter] unregisterHotKey:nextHotKey];
624 ITDebugLog(@"Done clearing hot keys.");
630 ITDebugLog(@"Setting up hot keys.");
632 if (playerRunningState == ITMTRemotePlayerNotRunning && ![[NetworkController sharedController] isConnectedToServer]) {
636 if ([df objectForKey:@"PlayPause"] != nil) {
637 ITDebugLog(@"Setting up play pause hot key.");
638 hotKey = [[ITHotKey alloc] init];
639 [hotKey setName:@"PlayPause"];
640 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PlayPause"]]];
641 [hotKey setTarget:self];
642 [hotKey setAction:@selector(playPause)];
643 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
646 if ([df objectForKey:@"NextTrack"] != nil) {
647 ITDebugLog(@"Setting up next track hot key.");
648 hotKey = [[ITHotKey alloc] init];
649 [hotKey setName:@"NextTrack"];
650 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"NextTrack"]]];
651 [hotKey setTarget:self];
652 [hotKey setAction:@selector(nextSong)];
653 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
656 if ([df objectForKey:@"PrevTrack"] != nil) {
657 ITDebugLog(@"Setting up previous track hot key.");
658 hotKey = [[ITHotKey alloc] init];
659 [hotKey setName:@"PrevTrack"];
660 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PrevTrack"]]];
661 [hotKey setTarget:self];
662 [hotKey setAction:@selector(prevSong)];
663 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
666 if ([df objectForKey:@"ShowPlayer"] != nil) {
667 ITDebugLog(@"Setting up show player hot key.");
668 hotKey = [[ITHotKey alloc] init];
669 [hotKey setName:@"ShowPlayer"];
670 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
671 [hotKey setTarget:self];
672 [hotKey setAction:@selector(showPlayer)];
673 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
676 if ([df objectForKey:@"TrackInfo"] != nil) {
677 ITDebugLog(@"Setting up track info hot key.");
678 hotKey = [[ITHotKey alloc] init];
679 [hotKey setName:@"TrackInfo"];
680 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"TrackInfo"]]];
681 [hotKey setTarget:self];
682 [hotKey setAction:@selector(showCurrentTrackInfo)];
683 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
686 if ([df objectForKey:@"UpcomingSongs"] != nil) {
687 ITDebugLog(@"Setting up upcoming songs hot key.");
688 hotKey = [[ITHotKey alloc] init];
689 [hotKey setName:@"UpcomingSongs"];
690 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"UpcomingSongs"]]];
691 [hotKey setTarget:self];
692 [hotKey setAction:@selector(showUpcomingSongs)];
693 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
696 if ([df objectForKey:@"ToggleLoop"] != nil) {
697 ITDebugLog(@"Setting up toggle loop hot key.");
698 hotKey = [[ITHotKey alloc] init];
699 [hotKey setName:@"ToggleLoop"];
700 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleLoop"]]];
701 [hotKey setTarget:self];
702 [hotKey setAction:@selector(toggleLoop)];
703 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
706 if ([df objectForKey:@"ToggleShuffle"] != nil) {
707 ITDebugLog(@"Setting up toggle shuffle hot key.");
708 hotKey = [[ITHotKey alloc] init];
709 [hotKey setName:@"ToggleShuffle"];
710 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShuffle"]]];
711 [hotKey setTarget:self];
712 [hotKey setAction:@selector(toggleShuffle)];
713 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
716 if ([df objectForKey:@"IncrementVolume"] != nil) {
717 ITDebugLog(@"Setting up increment volume hot key.");
718 hotKey = [[ITHotKey alloc] init];
719 [hotKey setName:@"IncrementVolume"];
720 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementVolume"]]];
721 [hotKey setTarget:self];
722 [hotKey setAction:@selector(incrementVolume)];
723 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
726 if ([df objectForKey:@"DecrementVolume"] != nil) {
727 ITDebugLog(@"Setting up decrement volume hot key.");
728 hotKey = [[ITHotKey alloc] init];
729 [hotKey setName:@"DecrementVolume"];
730 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementVolume"]]];
731 [hotKey setTarget:self];
732 [hotKey setAction:@selector(decrementVolume)];
733 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
736 if ([df objectForKey:@"IncrementRating"] != nil) {
737 ITDebugLog(@"Setting up increment rating hot key.");
738 hotKey = [[ITHotKey alloc] init];
739 [hotKey setName:@"IncrementRating"];
740 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementRating"]]];
741 [hotKey setTarget:self];
742 [hotKey setAction:@selector(incrementRating)];
743 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
746 if ([df objectForKey:@"DecrementRating"] != nil) {
747 ITDebugLog(@"Setting up decrement rating hot key.");
748 hotKey = [[ITHotKey alloc] init];
749 [hotKey setName:@"DecrementRating"];
750 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementRating"]]];
751 [hotKey setTarget:self];
752 [hotKey setAction:@selector(decrementRating)];
753 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
755 ITDebugLog(@"Finished setting up hot keys.");
758 - (void)showCurrentTrackInfo
760 ITMTRemotePlayerSource source = 0;
761 NSString *title = nil;
762 NSString *album = nil;
763 NSString *artist = nil;
764 NSString *composer = nil;
765 NSString *time = nil;
766 NSString *track = nil;
770 ITDebugLog(@"Showing track info status window.");
773 source = [[self currentRemote] currentSource];
774 title = [[self currentRemote] currentSongTitle];
776 [self networkError:localException];
780 if ( [df boolForKey:@"showAlbumArtwork"] ) {
781 NSSize oldSize, newSize;
783 art = [[self currentRemote] currentSongAlbumArt];
784 oldSize = [art size];
785 if (oldSize.width > oldSize.height) newSize = NSMakeSize(110,oldSize.height * (110.0f / oldSize.width));
786 else newSize = NSMakeSize(oldSize.width * (110.0f / oldSize.height),110);
787 art = [[[[NSImage alloc] initWithData:[art TIFFRepresentation]] autorelease] imageScaledSmoothlyToSize:newSize];
789 [self networkError:localException];
793 if ( [df boolForKey:@"showAlbum"] ) {
795 album = [[self currentRemote] currentSongAlbum];
797 [self networkError:localException];
801 if ( [df boolForKey:@"showArtist"] ) {
803 artist = [[self currentRemote] currentSongArtist];
805 [self networkError:localException];
809 if ( [df boolForKey:@"showComposer"] ) {
811 composer = [[self currentRemote] currentSongComposer];
813 [self networkError:localException];
817 if ( [df boolForKey:@"showTime"] ) {
819 time = [NSString stringWithFormat:@"%@: %@ / %@",
821 [[self currentRemote] currentSongElapsed],
822 [[self currentRemote] currentSongLength]];
824 [self networkError:localException];
828 if ( [df boolForKey:@"showTrackNumber"] ) {
833 trackNo = [[self currentRemote] currentSongTrack];
834 trackCount = [[self currentRemote] currentAlbumTrackCount];
836 [self networkError:localException];
839 if ( (trackNo > 0) || (trackCount > 0) ) {
840 track = [NSString stringWithFormat:@"%@: %i %@ %i",
841 @"Track", trackNo, @"of", trackCount];
845 if ( [df boolForKey:@"showTrackRating"] ) {
846 float currentRating = 0;
849 currentRating = [[self currentRemote] currentSongRating];
851 [self networkError:localException];
854 if (currentRating >= 0.0) {
855 rating = ( currentRating * 5 );
859 title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
861 ITDebugLog(@"Showing current track info status window.");
862 [statusWindowController showSongInfoWindowWithSource:source
873 - (void)showUpcomingSongs
877 numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
879 [self networkError:localException];
882 ITDebugLog(@"Showing upcoming songs status window.");
885 int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
886 NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
887 int curTrack = [[self currentRemote] currentSongIndex];
890 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
892 [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
896 if ([songList count] == 0) {
897 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
900 [statusWindowController showUpcomingSongsWindowWithTitles:songList];
902 [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
905 [self networkError:localException];
909 - (void)incrementVolume
912 float volume = [[self currentRemote] volume];
913 float dispVol = volume;
914 ITDebugLog(@"Incrementing volume.");
923 ITDebugLog(@"Setting volume to %f", volume);
924 [[self currentRemote] setVolume:volume];
926 // Show volume status window
927 [statusWindowController showVolumeWindowWithLevel:dispVol];
929 [self networkError:localException];
933 - (void)decrementVolume
936 float volume = [[self currentRemote] volume];
937 float dispVol = volume;
938 ITDebugLog(@"Decrementing volume.");
947 ITDebugLog(@"Setting volume to %f", volume);
948 [[self currentRemote] setVolume:volume];
950 //Show volume status window
951 [statusWindowController showVolumeWindowWithLevel:dispVol];
953 [self networkError:localException];
957 - (void)incrementRating
960 float rating = [[self currentRemote] currentSongRating];
961 ITDebugLog(@"Incrementing rating.");
963 if ([[self currentRemote] currentPlaylistIndex] == 0) {
964 ITDebugLog(@"No song playing, rating change aborted.");
972 ITDebugLog(@"Setting rating to %f", rating);
973 [[self currentRemote] setCurrentSongRating:rating];
975 //Show rating status window
976 [statusWindowController showRatingWindowWithRating:rating];
978 [self networkError:localException];
982 - (void)decrementRating
985 float rating = [[self currentRemote] currentSongRating];
986 ITDebugLog(@"Decrementing rating.");
988 if ([[self currentRemote] currentPlaylistIndex] == 0) {
989 ITDebugLog(@"No song playing, rating change aborted.");
997 ITDebugLog(@"Setting rating to %f", rating);
998 [[self currentRemote] setCurrentSongRating:rating];
1000 //Show rating status window
1001 [statusWindowController showRatingWindowWithRating:rating];
1003 [self networkError:localException];
1010 ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
1011 ITDebugLog(@"Toggling repeat mode.");
1012 switch (repeatMode) {
1013 case ITMTRemotePlayerRepeatOff:
1014 repeatMode = ITMTRemotePlayerRepeatAll;
1016 case ITMTRemotePlayerRepeatAll:
1017 repeatMode = ITMTRemotePlayerRepeatOne;
1019 case ITMTRemotePlayerRepeatOne:
1020 repeatMode = ITMTRemotePlayerRepeatOff;
1023 ITDebugLog(@"Setting repeat mode to %i", repeatMode);
1024 [[self currentRemote] setRepeatMode:repeatMode];
1026 //Show loop status window
1027 [statusWindowController showRepeatWindowWithMode:repeatMode];
1029 [self networkError:localException];
1033 - (void)toggleShuffle
1036 BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
1037 ITDebugLog(@"Toggling shuffle mode.");
1038 [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
1039 //Show shuffle status window
1040 ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
1041 [statusWindowController showShuffleWindow:newShuffleEnabled];
1043 [self networkError:localException];
1047 - (void)registerNowOK
1049 [[StatusWindow sharedWindow] setLocked:NO];
1050 [[StatusWindow sharedWindow] vanish:self];
1051 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1056 - (void)registerNowCancel
1058 [[StatusWindow sharedWindow] setLocked:NO];
1059 [[StatusWindow sharedWindow] vanish:self];
1060 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1062 [NSApp terminate:self];
1065 /*************************************************************************/
1067 #pragma mark NETWORK HANDLERS
1068 /*************************************************************************/
1070 - (void)setServerStatus:(BOOL)newStatus
1074 [networkController setServerStatus:YES];
1077 [networkController setServerStatus:NO];
1081 - (int)connectToServer
1084 ITDebugLog(@"Attempting to connect to shared remote.");
1085 result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
1088 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1089 currentRemote = [[[networkController networkObject] remote] retain];
1091 [self setupHotKeys];
1092 //playerRunningState = ITMTRemotePlayerRunning;
1093 playerRunningState = [[self currentRemote] playerRunningState];
1095 [refreshTimer invalidate];
1096 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1098 selector:@selector(timerUpdate)
1100 repeats:YES] retain];
1102 ITDebugLog(@"Connection successful.");
1104 } else if (result == 0) {
1105 ITDebugLog(@"Connection failed.");
1106 currentRemote = [remoteArray objectAtIndex:0];
1109 //Do something about the password being invalid
1110 ITDebugLog(@"Connection failed.");
1111 currentRemote = [remoteArray objectAtIndex:0];
1116 - (BOOL)disconnectFromServer
1118 ITDebugLog(@"Disconnecting from shared remote.");
1120 [currentRemote release];
1121 currentRemote = [remoteArray objectAtIndex:0];
1122 [networkController disconnect];
1124 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
1125 [self applicationLaunched:nil];
1127 [self applicationTerminated:nil];
1133 - (void)checkForRemoteServer
1135 [self checkForRemoteServerAndConnectImmediately:NO];
1138 - (void)checkForRemoteServerAndConnectImmediately:(BOOL)connectImmediately
1140 ITDebugLog(@"Checking for remote server.");
1141 [NSThread detachNewThreadSelector:@selector(runRemoteServerCheck:) toTarget:self withObject:[NSNumber numberWithBool:connectImmediately]];
1144 - (void)runRemoteServerCheck:(id)sender
1146 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1147 ITDebugLog(@"Remote server check running.");
1148 if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1149 ITDebugLog(@"Remote server found.");
1150 if ([sender boolValue]) {
1151 [self performSelectorOnMainThread:@selector(connectToServer) withObject:nil waitUntilDone:NO];
1153 [self performSelectorOnMainThread:@selector(remoteServerFound:) withObject:nil waitUntilDone:NO];
1156 ITDebugLog(@"Remote server not found.");
1157 [self performSelectorOnMainThread:@selector(remoteServerNotFound:) withObject:nil waitUntilDone:NO];
1162 - (void)remoteServerFound:(id)sender
1164 if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1165 [[StatusWindowController sharedController] showReconnectQueryWindow];
1169 - (void)remoteServerNotFound:(id)sender
1171 if (![[NetworkController sharedController] isConnectedToServer]) {
1172 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1176 - (void)networkError:(NSException *)exception
1178 ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1179 if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1180 //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);
1181 [[StatusWindowController sharedController] showNetworkErrorQueryWindow];
1182 if ([self disconnectFromServer]) {
1183 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1184 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1186 ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1193 /*if ([self connectToServer] == 0) {
1194 [NSTimer scheduledTimerWithTimeInterval:90.0 target:self selector:@selector(checkForRemoteServer) userInfo:nil repeats:NO];
1196 [self checkForRemoteServerAndConnectImmediately:YES];
1197 [[StatusWindow sharedWindow] setLocked:NO];
1198 [[StatusWindow sharedWindow] vanish:self];
1199 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1202 - (void)cancelReconnect
1204 [[StatusWindow sharedWindow] setLocked:NO];
1205 [[StatusWindow sharedWindow] vanish:self];
1206 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1209 /*************************************************************************/
1211 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1212 /*************************************************************************/
1214 - (void)applicationLaunched:(NSNotification *)note
1217 if (!note || ([[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer])) {
1218 ITDebugLog(@"Remote application launched.");
1219 playerRunningState = ITMTRemotePlayerRunning;
1220 [[self currentRemote] begin];
1221 [self setLatestSongIdentifier:@""];
1223 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1225 selector:@selector(timerUpdate)
1227 repeats:YES] retain];
1228 //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1229 [self setupHotKeys];
1232 [self networkError:localException];
1236 - (void)applicationTerminated:(NSNotification *)note
1239 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]] && ![[NetworkController sharedController] isConnectedToServer]) {
1240 ITDebugLog(@"Remote application terminated.");
1241 playerRunningState = ITMTRemotePlayerNotRunning;
1242 [[self currentRemote] halt];
1243 [refreshTimer invalidate];
1244 [refreshTimer release];
1246 [self clearHotKeys];
1248 if ([df objectForKey:@"ShowPlayer"] != nil) {
1250 ITDebugLog(@"Setting up show player hot key.");
1251 hotKey = [[ITHotKey alloc] init];
1252 [hotKey setName:@"ShowPlayer"];
1253 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1254 [hotKey setTarget:self];
1255 [hotKey setAction:@selector(showPlayer)];
1256 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1260 [self networkError:localException];
1265 /*************************************************************************/
1267 #pragma mark NSApplication DELEGATE METHODS
1268 /*************************************************************************/
1270 - (void)applicationWillTerminate:(NSNotification *)note
1272 [networkController stopRemoteServerSearch];
1273 [self clearHotKeys];
1274 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1278 /*************************************************************************/
1280 #pragma mark DEALLOCATION METHOD
1281 /*************************************************************************/
1285 [self applicationTerminated:nil];
1287 [statusItem release];
1288 [statusWindowController release];
1289 [menuController release];
1290 [networkController release];