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 if ([self connectToServer] == 0) {
93 [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
97 //Setup for notification of the remote player launching or quitting
98 [[[NSWorkspace sharedWorkspace] notificationCenter]
100 selector:@selector(applicationTerminated:)
101 name:NSWorkspaceDidTerminateApplicationNotification
104 [[[NSWorkspace sharedWorkspace] notificationCenter]
106 selector:@selector(applicationLaunched:)
107 name:NSWorkspaceDidLaunchApplicationNotification
110 if ( ! [df objectForKey:@"menu"] ) { // If this is nil, defaults have never been registered.
111 [[PreferencesController sharedPrefs] registerDefaults];
114 if ([df boolForKey:@"ITMTNoStatusItem"]) {
117 [StatusItemHack install];
118 statusItem = [[ITStatusItem alloc]
119 initWithStatusBar:[NSStatusBar systemStatusBar]
120 withLength:NSSquareStatusItemLength];
123 bling = [[MTBlingController alloc] init];
125 registerTimer = [[NSTimer scheduledTimerWithTimeInterval:10.0
127 selector:@selector(blingTime)
129 repeats:YES] retain];
132 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
133 [self applicationLaunched:nil];
135 if ([df boolForKey:@"LaunchPlayerWithMT"])
138 [self applicationTerminated:nil];
141 [self networkError:localException];
144 [statusItem setImage:[NSImage imageNamed:@"MenuNormal"]];
145 [statusItem setAlternateImage:[NSImage imageNamed:@"MenuInverted"]];
147 [networkController startRemoteServerSearch];
151 - (ITMTRemote *)loadRemote
153 NSString *folderPath = [[NSBundle mainBundle] builtInPlugInsPath];
154 ITDebugLog(@"Gathering remotes.");
156 NSArray *bundlePathList = [NSBundle pathsForResourcesOfType:@"remote" inDirectory:folderPath];
157 NSEnumerator *enumerator = [bundlePathList objectEnumerator];
158 NSString *bundlePath;
160 while ( (bundlePath = [enumerator nextObject]) ) {
161 NSBundle* remoteBundle = [NSBundle bundleWithPath:bundlePath];
164 Class remoteClass = [remoteBundle principalClass];
166 if ([remoteClass conformsToProtocol:@protocol(ITMTRemote)] &&
167 [remoteClass isKindOfClass:[NSObject class]]) {
168 id remote = [remoteClass remote];
169 ITDebugLog(@"Adding remote at path %@", bundlePath);
170 [remoteArray addObject:remote];
175 // if ( [remoteArray count] > 0 ) { // UNCOMMENT WHEN WE HAVE > 1 PLUGIN
176 // if ( [remoteArray count] > 1 ) {
177 // [remoteArray sortUsingSelector:@selector(sortAlpha:)];
179 // [self loadModuleAccessUI]; //Comment out this line to disable remote visibility
182 // NSLog(@"%@", [remoteArray objectAtIndex:0]); //DEBUG
183 return [remoteArray objectAtIndex:0];
186 /*************************************************************************/
188 #pragma mark INSTANCE METHODS
189 /*************************************************************************/
191 /*- (void)startTimerInNewThread
193 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
194 NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
195 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:0.5
197 selector:@selector(timerUpdate)
199 repeats:YES] retain];
201 ITDebugLog(@"Timer started.");
205 - (void)setBlingTime:(NSDate*)date
207 NSMutableDictionary *globalPrefs;
209 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
211 [globalPrefs setObject:date forKey:@"ITMTTrialStart"];
212 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
214 [globalPrefs removeObjectForKey:@"ITMTTrialStart"];
215 [globalPrefs removeObjectForKey:@"ITMTTrialVers"];
217 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
219 [globalPrefs release];
222 - (NSDate*)getBlingTime
225 return [[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialStart"];
230 NSDate *now = [NSDate date];
231 if (![self blingBling]) {
232 if ( (! [self getBlingTime] ) || ([now timeIntervalSinceDate:[self getBlingTime]] < 0) ) {
233 [self setBlingTime:now];
234 } else if ([[[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialVers"] intValue] < MT_CURRENT_VERSION) {
235 if ([now timeIntervalSinceDate:[self getBlingTime]] >= 345600) {
236 [self setBlingTime:[now addTimeInterval:-259200]];
238 NSMutableDictionary *globalPrefs;
240 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
241 [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
242 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
244 [globalPrefs release];
248 if ( ([now timeIntervalSinceDate:[self getBlingTime]] >= 604800) && (blinged != YES) ) {
250 [statusItem setEnabled:NO];
252 if ([refreshTimer isValid]) {
253 [refreshTimer invalidate];
255 [statusWindowController showRegistrationQueryWindow];
259 [statusItem setEnabled:YES];
261 if (![refreshTimer isValid]) {
262 [refreshTimer release];
263 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
265 selector:@selector(timerUpdate)
267 repeats:YES] retain];
271 [self setBlingTime:nil];
282 if ( ! ([bling checkDone] == 2475) ) {
289 - (BOOL)songIsPlaying
291 NSString *identifier = nil;
293 identifier = [[self currentRemote] playerStateUniqueIdentifier];
295 [self networkError:localException];
297 return ( ! ([identifier isEqualToString:@"0-0"]) );
300 - (BOOL)radioIsPlaying
302 ITMTRemotePlayerPlaylistClass class = nil;
304 class = [[self currentRemote] currentPlaylistClass];
306 [self networkError:localException];
308 return (class == ITMTRemotePlayerRadioPlaylist );
313 NSString *identifier = nil;
315 identifier = [[self currentRemote] playerStateUniqueIdentifier];
317 [self networkError:localException];
319 return ( ! [identifier isEqualToString:_latestSongIdentifier] );
322 - (NSString *)latestSongIdentifier
324 return _latestSongIdentifier;
327 - (void)setLatestSongIdentifier:(NSString *)newIdentifier
329 ITDebugLog(@"Setting latest song identifier:");
330 ITDebugLog(@" - Identifier: %@", newIdentifier);
331 [_latestSongIdentifier autorelease];
332 _latestSongIdentifier = [newIdentifier retain];
337 if ([networkController isConnectedToServer]) {
338 [statusItem setMenu:[menuController menu]];
341 if ( [self songChanged] && (timerUpdating != YES) && (playerRunningState == ITMTRemotePlayerRunning) ) {
342 ITDebugLog(@"The song changed.");
344 if ([df boolForKey:@"runScripts"]) {
345 NSArray *scripts = [[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"]];
346 NSEnumerator *scriptsEnum = [scripts objectEnumerator];
347 NSString *nextScript;
348 ITDebugLog(@"Running AppleScripts for song change.");
349 while ( (nextScript = [scriptsEnum nextObject]) ) {
351 NSAppleScript *currentScript = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"] stringByAppendingPathComponent:nextScript]] error:&error];
352 ITDebugLog(@"Running script: %@", nextScript);
353 if (!currentScript || ![currentScript executeAndReturnError:nil]) {
354 ITDebugLog(@"Error running script %@.", nextScript);
356 [currentScript release];
363 latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
364 [menuController rebuildSubmenus];
366 if ( [df boolForKey:@"showSongInfoOnChange"] ) {
367 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
370 [self setLatestSongIdentifier:[[self currentRemote] playerStateUniqueIdentifier]];
372 //Create the tooltip for the status item
373 if ( [df boolForKey:@"showToolTip"] ) {
374 NSString *artist = [[self currentRemote] currentSongArtist];
375 NSString *title = [[self currentRemote] currentSongTitle];
377 ITDebugLog(@"Creating status item tooltip.");
379 toolTip = [NSString stringWithFormat:@"%@ - %@", artist, title];
383 toolTip = @"No Song Playing";
385 [statusItem setToolTip:toolTip];
387 [statusItem setToolTip:nil];
390 [self networkError:localException];
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 path = [[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];
781 if ( [df boolForKey:@"showAlbum"] ) {
783 album = [[self currentRemote] currentSongAlbum];
785 [self networkError:localException];
789 if ( [df boolForKey:@"showArtist"] ) {
791 artist = [[self currentRemote] currentSongArtist];
793 [self networkError:localException];
797 if ( [df boolForKey:@"showComposer"] ) {
799 composer = [[self currentRemote] currentSongComposer];
801 [self networkError:localException];
805 if ( [df boolForKey:@"showTime"] ) {
807 time = [NSString stringWithFormat:@"%@: %@ / %@",
809 [[self currentRemote] currentSongElapsed],
810 [[self currentRemote] currentSongLength]];
812 [self networkError:localException];
816 if ( [df boolForKey:@"showTrackNumber"] ) {
821 trackNo = [[self currentRemote] currentSongTrack];
822 trackCount = [[self currentRemote] currentAlbumTrackCount];
824 [self networkError:localException];
827 if ( (trackNo > 0) || (trackCount > 0) ) {
828 track = [NSString stringWithFormat:@"%@: %i %@ %i",
829 @"Track", trackNo, @"of", trackCount];
833 if ( [df boolForKey:@"showTrackRating"] ) {
834 float currentRating = 0;
837 currentRating = [[self currentRemote] currentSongRating];
839 [self networkError:localException];
842 if (currentRating >= 0.0) {
843 rating = ( currentRating * 5 );
847 if ( [df boolForKey:@"showAlbumArtwork"] ) {
848 NSSize oldSize, newSize;
850 art = [[self currentRemote] currentSongAlbumArt];
851 oldSize = [art size];
852 if (oldSize.width > oldSize.height) newSize = NSMakeSize(110,oldSize.height * (110.0f / oldSize.width));
853 else newSize = NSMakeSize(oldSize.width * (110.0f / oldSize.height),110);
854 art = [[[[NSImage alloc] initWithData:[art TIFFRepresentation]] autorelease] imageScaledSmoothlyToSize:newSize];
856 [self networkError:localException];
861 title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
863 ITDebugLog(@"Showing current track info status window.");
864 [statusWindowController showSongInfoWindowWithSource:source
875 - (void)showUpcomingSongs
879 numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
881 [self networkError:localException];
884 ITDebugLog(@"Showing upcoming songs status window.");
887 int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
888 NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
889 int curTrack = [[self currentRemote] currentSongIndex];
892 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
894 [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
898 if ([songList count] == 0) {
899 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
902 [statusWindowController showUpcomingSongsWindowWithTitles:songList];
904 [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
907 [self networkError:localException];
911 - (void)incrementVolume
914 float volume = [[self currentRemote] volume];
915 float dispVol = volume;
916 ITDebugLog(@"Incrementing volume.");
925 ITDebugLog(@"Setting volume to %f", volume);
926 [[self currentRemote] setVolume:volume];
928 // Show volume status window
929 [statusWindowController showVolumeWindowWithLevel:dispVol];
931 [self networkError:localException];
935 - (void)decrementVolume
938 float volume = [[self currentRemote] volume];
939 float dispVol = volume;
940 ITDebugLog(@"Decrementing volume.");
949 ITDebugLog(@"Setting volume to %f", volume);
950 [[self currentRemote] setVolume:volume];
952 //Show volume status window
953 [statusWindowController showVolumeWindowWithLevel:dispVol];
955 [self networkError:localException];
959 - (void)incrementRating
962 float rating = [[self currentRemote] currentSongRating];
963 ITDebugLog(@"Incrementing rating.");
965 if ([[self currentRemote] currentPlaylistIndex] == 0) {
966 ITDebugLog(@"No song playing, rating change aborted.");
974 ITDebugLog(@"Setting rating to %f", rating);
975 [[self currentRemote] setCurrentSongRating:rating];
977 //Show rating status window
978 [statusWindowController showRatingWindowWithRating:rating];
980 [self networkError:localException];
984 - (void)decrementRating
987 float rating = [[self currentRemote] currentSongRating];
988 ITDebugLog(@"Decrementing rating.");
990 if ([[self currentRemote] currentPlaylistIndex] == 0) {
991 ITDebugLog(@"No song playing, rating change aborted.");
999 ITDebugLog(@"Setting rating to %f", rating);
1000 [[self currentRemote] setCurrentSongRating:rating];
1002 //Show rating status window
1003 [statusWindowController showRatingWindowWithRating:rating];
1005 [self networkError:localException];
1012 ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
1013 ITDebugLog(@"Toggling repeat mode.");
1014 switch (repeatMode) {
1015 case ITMTRemotePlayerRepeatOff:
1016 repeatMode = ITMTRemotePlayerRepeatAll;
1018 case ITMTRemotePlayerRepeatAll:
1019 repeatMode = ITMTRemotePlayerRepeatOne;
1021 case ITMTRemotePlayerRepeatOne:
1022 repeatMode = ITMTRemotePlayerRepeatOff;
1025 ITDebugLog(@"Setting repeat mode to %i", repeatMode);
1026 [[self currentRemote] setRepeatMode:repeatMode];
1028 //Show loop status window
1029 [statusWindowController showRepeatWindowWithMode:repeatMode];
1031 [self networkError:localException];
1035 - (void)toggleShuffle
1038 BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
1039 ITDebugLog(@"Toggling shuffle mode.");
1040 [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
1041 //Show shuffle status window
1042 ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
1043 [statusWindowController showShuffleWindow:newShuffleEnabled];
1045 [self networkError:localException];
1049 - (void)registerNowOK
1051 [[StatusWindow sharedWindow] setLocked:NO];
1052 [[StatusWindow sharedWindow] vanish:self];
1053 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1058 - (void)registerNowCancel
1060 [[StatusWindow sharedWindow] setLocked:NO];
1061 [[StatusWindow sharedWindow] vanish:self];
1062 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1064 [NSApp terminate:self];
1067 /*************************************************************************/
1069 #pragma mark NETWORK HANDLERS
1070 /*************************************************************************/
1072 - (void)setServerStatus:(BOOL)newStatus
1076 [networkController setServerStatus:YES];
1079 [networkController setServerStatus:NO];
1083 - (int)connectToServer
1086 ITDebugLog(@"Attempting to connect to shared remote.");
1087 result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
1090 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1091 currentRemote = [[[networkController networkObject] remote] retain];
1092 [refreshTimer invalidate];
1093 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1095 selector:@selector(timerUpdate)
1097 repeats:YES] retain];
1099 ITDebugLog(@"Connection successful.");
1101 } else if (result == 0) {
1102 ITDebugLog(@"Connection failed.");
1103 currentRemote = [remoteArray objectAtIndex:0];
1106 //Do something about the password being invalid
1107 ITDebugLog(@"Connection failed.");
1108 currentRemote = [remoteArray objectAtIndex:0];
1113 - (BOOL)disconnectFromServer
1115 ITDebugLog(@"Disconnecting from shared remote.");
1117 [currentRemote release];
1118 currentRemote = [remoteArray objectAtIndex:0];
1119 [networkController disconnect];
1124 - (void)checkForRemoteServer:(NSTimer *)timer
1126 ITDebugLog(@"Checking for remote server.");
1127 if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1128 ITDebugLog(@"Remote server found.");
1130 if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1131 [[StatusWindowController sharedController] showReconnectQueryWindow];
1134 ITDebugLog(@"Remote server not found.");
1138 - (void)networkError:(NSException *)exception
1140 ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1141 if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1142 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);
1143 if ([self disconnectFromServer]) {
1144 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1145 [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
1147 ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1154 if ([self connectToServer] == 0) {
1155 [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
1157 [[StatusWindow sharedWindow] setLocked:NO];
1158 [[StatusWindow sharedWindow] vanish:self];
1159 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1162 - (void)cancelReconnect
1164 [[StatusWindow sharedWindow] setLocked:NO];
1165 [[StatusWindow sharedWindow] vanish:self];
1166 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1169 /*************************************************************************/
1171 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1172 /*************************************************************************/
1174 - (void)applicationLaunched:(NSNotification *)note
1177 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]]) {
1178 ITDebugLog(@"Remote application launched.");
1179 playerRunningState = ITMTRemotePlayerRunning;
1180 [[self currentRemote] begin];
1181 [self setLatestSongIdentifier:@""];
1183 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1185 selector:@selector(timerUpdate)
1187 repeats:YES] retain];
1188 //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1189 [self setupHotKeys];
1192 [self networkError:localException];
1196 - (void)applicationTerminated:(NSNotification *)note
1199 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]]) {
1200 ITDebugLog(@"Remote application terminated.");
1201 playerRunningState = ITMTRemotePlayerNotRunning;
1202 [[self currentRemote] halt];
1203 [refreshTimer invalidate];
1204 [refreshTimer release];
1206 [self clearHotKeys];
1208 if ([df objectForKey:@"ShowPlayer"] != nil) {
1210 ITDebugLog(@"Setting up show player hot key.");
1211 hotKey = [[ITHotKey alloc] init];
1212 [hotKey setName:@"ShowPlayer"];
1213 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1214 [hotKey setTarget:self];
1215 [hotKey setAction:@selector(showPlayer)];
1216 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1220 [self networkError:localException];
1225 /*************************************************************************/
1227 #pragma mark NSApplication DELEGATE METHODS
1228 /*************************************************************************/
1230 - (void)applicationWillTerminate:(NSNotification *)note
1232 [networkController stopRemoteServerSearch];
1233 [self clearHotKeys];
1234 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1238 /*************************************************************************/
1240 #pragma mark DEALLOCATION METHOD
1241 /*************************************************************************/
1245 [self applicationTerminated:nil];
1247 [statusItem release];
1248 [statusWindowController release];
1249 [menuController release];
1250 [networkController release];